I'm writing a function that takes a text as input, and perform replacements in the text. For instance, I look for all the instances of "blue" and replace that with "red". I use regexp to detect the strings I'm looking for, which is used by the (text).replace function. The problem is that I do a very high number of those text.replace, and I want a way to parse through the text string by string, and if it matches anything I want, I'll perform the replacement (instead of looking for "blue" in the entire text, then "green" in the entire text, and so on). I believe this is way more efficient, but how can I do this exactly?
Thanks in advance.
4 Answers 4
You can do that with a regex as well, and looking for multiple substrings with a callback to replace each one with the same regex.
That would scan the string once, but of course the callback can make it less efficient, depending on what you do in the callback.
text = text.replace(/(blue|red|green)/g, function(x) {
var ret = '';
switch (x) {
case 'blue' :
ret = 'azul';
break;
case 'green' :
ret = 'verde';
break;
case 'red' :
ret = 'rojo';
break;
default :
ret = 'color';
}
return ret;
});
a little verbose, but you get the point.
This can be extended, for instance using a map for the replacements
var replacements = {
'blue' : 'azul',
'green': 'verde',
'red' : 'rojo'
}
var reg = new RegExp('(' + Object.keys(replacements).join('|') + ')','g');
text = text.replace(reg, function(x) {
return replacements[x];
});
9 Comments
return ({"blue":"azul","green":"verde","red:"rojo"})[x] || "color"; is less verbose.OR. If it enters the function there will always be a match.|) is an OR in the regex, seperating the phrases to search for etc.You can have a regex that matches all of your string an use a replacement function to perform specific actions based on the match.
'redgreenblue'.replace(/red|green|blue/g, function (color) {
switch (color) {
case 'red': return 'RED';
case 'green': return 'GREEN';
case 'blue': return '';
}
});
1 Comment
I think that using Regular Expressions is the best way to do it, browsers are very optimized to work with them and other solutions may make your code much more complicated.
var text = "this is a test";
var replacements = { 'this': 'that'};
for (var source in replacements){
var target = replacements[source],
expression = new RegExp(source,"g");
text = text.replace(expression, target);
}
Comments
Others were quicker. Here is my proposal anyway (slightly different, but same idea as others already wrote), using an alternation as regex, and a function with hash access for the substitution:
var text = "...";
var words = { "red":"FF0000", "green":"00FF00", "blue":"0000FF", "yellow":"FFFF00", ... };
var pattern = new RegExp( Object.keys(words).join("|"), "g" );
var newText = text.replace( pattern, function(match) {
return words[match]
});
See it work on http://ideone.com/RsuxJW