0

i have a simple smily parser code :

for (var key in smiles) {
  text = text.replace(key  , smiles[key]);
}
return text;

so the problem is , this will only replace the first one so i've switched to global replace

for (var key in smiles) {
  var r =  '/'+key+'/g';
  console.log(r);
  text = text.replace(r  , smiles[key]);
}

in console i have :

/:)/g
/;)/g
/:(/g

which seems to be ok , but it wont replace any of these codes :) ;) :( whats wrong ?

max
  • 3,614
  • 9
  • 59
  • 107

2 Answers2

1

A regular expression literal (/foo/g) is not the same as a string that looks like a regular expression literal ("/foo/g").

You can create regular expressions dynamically using the RegExp constructor:

var r = new RegExp(key, 'g');

And that’s the point at which you’ll get parenthesis-related errors. You can escape your values to put in a regular expression – put together in the nicest way, it might look something like this:

function escapeRegex(text) {
    return text.replace(/[[{}()*+?.\\^$|]/g, "\\$&");
}

function replaceAll(str, map) {
    var re = new RegExp(Object.keys(map).map(escapeRegex).join("|"), "g");

    return str.replace(re, function(m) {
        return map[m];
    });
}
Community
  • 1
  • 1
rninty
  • 1,072
  • 6
  • 10
  • yeah , i get : Uncaught SyntaxError: Invalid regular expression: /:)/: Unmatched ')' – max Nov 15 '13 at 05:30
  • A bit nasty having *map* as a local variable and also calling the *map* method. – RobG Nov 15 '13 at 05:36
0

Just keep looping through the text and replacing the smiley until there are no more occurrences:-

for (var key in smiles) {
    while (text.indexOf(key) > -1) {
        text = text.replace(key, smiles[key]);
    }
}
return text;
dav1dsm1th
  • 1,687
  • 2
  • 20
  • 24