3

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?

baik
  • 993
  • 2
  • 14
  • 21

1 Answers1

9
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

Ivan Castellanos
  • 8,041
  • 1
  • 47
  • 42