views:

106

answers:

2

Hello,

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} example to {3}" (order is intact)

the string will undergo some processing and then

string  = " {1} is a {2} numbers to {3}" (order is intact)

tokens are again replaced back to the string likem so that the string becomes

string  = " this is a good number to show"

how to make sure that the pattern is matched and the same tokens are replaced

for example /[gG]ood/ is a pattern to search and replaced later with appropriate "case".Or in other words if ^\s*[0-9]+. is the pattern the matched string needs to be stored and replace to form the original text as it was

How should it be implemented so that the process is done at high performance ?

Thanks in advance.

A: 

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:

var string = "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(new RegExp(tokens[i], "g"),"{"+i+"}");
}
// string processing here
for (var i = 0; i < tokens.length; i++) {
    string.replace(new RegExp("{"+i+"}","g"),tokens[i]);
}
Dan
Thanks a lot. This is what I was trying to do.
Sourabh
That only works if the strings to be replaced do not contain any special characters. Sadly, javascript has no built-in regex escaping capabilities.
Tgr
Also, if it is really high-performance, using regexes for simple string substitution is not necessarily a good idea.
Tgr
And that's not really how you use the regex constructor.
Tgr
`new RegExp("/foo/g")` will not match on `foo`, only on `/foo/g`. You would need `new RegExp("foo", "g")`.
Tgr
As for performance, it depends on circumstances. Lot of short strings, long string with lots of different tokens, etc. If tokens occur only once, initializing the regex objects is an unnecessary overhead, and the global modifier slows it down even more. Or it might make sense to chain all tokens into a single regexp (only one pass). Again, depends on the circumstances.
Tgr
+1  A: 
var string = "this is a good example to show"
var search = ["this","good","show"] // this is how you define a literal array

for (var i = 0, len = search.length; i < len; i++) {
   string.replace(RegExp(search[i], "g"), "{" + (i+1) + "}")
}

//... do stuff

string.replace(/\{(\d+)\}/, function(match, number) {
  if (+number > 0)
    return search[+number - 1];
});
RoToRa
Thanks for the answer
Sourabh