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
  • 212,985
  • 98
  • 444
  • 485
Derek
  • 2,010
  • 1
  • 23
  • 35

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
  • 837,282
  • 173
  • 1,862
  • 1,933
  • 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
  • 20,881
  • 3
  • 42
  • 67