Skip to content Skip to sidebar Skip to footer

Find And Replace Tokens In Javascript

I have to do something like this string = ' this is a good example to show' search = array {this,good,show} find and replace them with a token like string = ' {1} is a {2} exa

Solution 1:

You don't mention anything about multiple occurrences of the same token in the string, I guess you'll be replacing all occurrences.

It would go something like this:

varstring = "This is a good example to show, this example to show is good";
var tokens = ['this','good','example'];

for (var i = 0; i < tokens.length; i++) {
    string.replace(newRegExp(tokens[i], "g"),"{"+i+"}");
}
// string processing herefor (var i = 0; i < tokens.length; i++) {
    string.replace(newRegExp("{"+i+"}","g"),tokens[i]);
}

Solution 2:

varstring = "this is a good example to show"var search = ["this","good","show"] // this is how you define a literal arrayfor (var i = 0, len = search.length; i < len; i++) {
   string.replace(RegExp(search[i], "g"), "{" + (i+1) + "}")
}

//... do stuffstring.replace(/\{(\d+)\}/, function(match, number) {
  if (+number > 0)
    return search[+number - 1];
});

Post a Comment for "Find And Replace Tokens In Javascript"