1

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.

0

4 Answers 4

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];
});
Sign up to request clarification or add additional context in comments.

9 Comments

return ({"blue":"azul","green":"verde","red:"rojo"})[x] || "color"; is less verbose.
@BenjaminGruenbaum - Indeed, an object with matching keys would be less verbose, I'll add that as an example as well, I just typed it very verbose to make a point really.
There is no reason for a OR. If it enters the function there will always be a match.
@BenjaminGruenbaum - I did it a little differently, still verbose I guess, but the regex auto-updates when the object is changed !
Sure you can, as long as the regex is valid you can searh for anything really, and the pipe (|) is an OR in the regex, seperating the phrases to search for etc.
|
3

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

Never thought the replace method would work like that. Sir you are an scholar. Thanks
1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.