0

I have a string of text that has the value of the selected text. Id like to do a replace() of this text in a given div of text.

so I know I can do that with the following:

myelement.replace(/foo/g, 'bar');

However I need to do it with my string ie:

myelement.replace(/*mystring*/g, 'bar');

So I tried:

mystring = '/'+mystring+'/g';
myelement.replace(mystring, 'bar');

Which didnt work, so i tried (which i knew wouldn't work):

myelement.replace(/+mystring+/g, 'bar');

So how can i do this?

I've coded something up for you guys in jsfiddle --> HELP ME PLEASE!

Alex
  • 8,875
  • 2
  • 27
  • 44
  • Btw, `$('#myelement')` will return a jQuery object, not a string. If you want to replace the content of the element, have a look at the `.html()` and `.text()` methods: http://api.jquery.com/ – Felix Kling Mar 07 '12 at 11:51
  • You need to create a `new RegExp()` – elclanrs Mar 07 '12 at 11:51
  • @Felix Kling thanks mate. I missed typed this in the question (now ammended). It was correct in the jsfiddle example. – Alex Mar 07 '12 at 11:53

3 Answers3

2

http://jsfiddle.net/2rG2V/

The change being to use new RegExp(st, "g") instead of creating the string as you did before. /test/g is just a shortcut way of creating a RegExp object.

Chris
  • 27,210
  • 6
  • 71
  • 92
  • Thanks for you answer, I check [another answer]http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript that @Felix Kling alerted me to. So i will accept your answer when I can. Big thanks to Felix too. – Alex Mar 07 '12 at 11:58
  • Yeah, I hadn't noticed that Felix had pointed out a dupe when I wrote this answer. – Chris Mar 07 '12 at 12:00
0

simply replace your

regSt = '/'+st+'/g';  

with

regSt = new RegExp(st,'g');

more info on regExp http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Liviu
  • 452
  • 1
  • 5
  • 14
0
eval('myelement.replace(/' + mystring + '/g, "bar");');
F.P
  • 17,421
  • 34
  • 123
  • 189