Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery global regex for replace with variable

in the following example I am trying to replace all instances of the newname variable with -, however newname in my example is handled as text, rather than a as variable.

var newname = 'test';

var lastname = $(this).attr('name').replace(/newname/g, "-");

Can anyone help out?

like image 318
baik Avatar asked Aug 16 '26 12:08

baik


1 Answers

var newname = 'test';
var regex = new RegExp(newname,"g")
var lastname = $(this).attr('name').replace(regex, "-");

More info:

http://smyck.net/2006/08/11/javascript-dynamic-regular-expresions/ http://fyneworks.blogspot.com/2007/04/dynamic-regular-expressions-in.html

like image 59
Ivan Castellanos Avatar answered Aug 19 '26 02:08

Ivan Castellanos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!