el_quick
el_quick

Reputation: 4756

Javascript regex match and replace percent symbol

sorry for my english

I am trying replace everything that is not %d, %m or %Y from a string, I have been trying but I do not get it, here is my best attempt code:

var old_string = "%l %d de %M de %Y (Semana %W)";               
string = old_string.replace(/[^(%d|%m|%Y)]/g, " ");             
alert(old_string + " <----> " + string);

Some help? What am I doing wrong?

Upvotes: 3

Views: 6113

Answers (3)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

If I understand correctly, you want to the substrings %d, %m and %Y from your string. I assume you want one space between each match, and want to retain the original order of occurrence.

You can do this using String.match() and Array.join(), like so:

var old_string = "%l %d de %m de %Y (Semana %W)";
var matches = old_string.match(/%[dmY]/g);
var new_string = matches.join(" ");

alert(new_string); // "%d %m %Y"

Edit: here is a working demo: http://jsfiddle.net/PPvG/Gv3rX/1/

Edit (2): I realised the regular expression could be simplified further.

Upvotes: 3

Eder
Eder

Reputation: 1884

If I understood correctly, your resulting string would be %d de de %Y (Semana), which makes no sense to me since I'm a Spanish user. But here is an alternative to your regex sugestion.

var old_string = "%l %d de %M de %Y (Semana %W)";
var new_string = "";

var i = 0;
while (i < old_string.length) {
    var char = old_string[i];

    new_string += char; 
    if (char == "%") {
        ++i;

        var next_char = old_string[i];

        switch (next_char) {
            case "d":
            case "m":
            case "Y":
                new_string += next_char;
                break;
            default:
                new_string = new_string.substring(0, new_string.length - 2);
        }
    }

    ++i;
}


alert(new_string);

Upvotes: 0

murgatroid99
murgatroid99

Reputation: 20297

In your code you are using character classes incorrectly. Your regular expression will match any single character that is not one of (%d|mY). Instead you probably want to use negative lookahead to check that the string you are matching is not one of the specified strings. The following regular expression should do it:

/(?!(.*?)%(d|m|Y).*).*/

This will replace strings of any length that do not contain the specified strings with a single space.

Upvotes: 0

Related Questions