1

I'm looking for an easy way to turn this string:

(java || javascript) && vbscript

Into this string:

(str.search('java') || str.search('javascript')) && str.search('vbscript')

ie replace each word in the string with str.search('" + word + "')

I've looked at mystring.match(/[-\w]+/g); which will pull any words out into an array (but not their position)

John Conde
  • 217,595
  • 99
  • 455
  • 496
Derek
  • 2,092
  • 1
  • 24
  • 38

2 Answers2

4

You can call replace:

mystring.replace(/[-\w]+/g, "str.search('$&')");

Note that this is an XSS hole, since the user input can contain 's.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks for the quick response. When I try that it outputs (str.search('$0') || str.search('$0')) && str.search('$0') Am I being daft? – Derek May 01 '12 at 15:02
0

Just a fixed version with correct capture and using 1 as backtrack index. See details in "Specifying a string as a parameter" section of String.replace.

mystring.replace(/([-\w]+)/g, "str.search('$1')");
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68