admin管理员组

文章数量:1326330

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?

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?

Share Improve this question asked Oct 25, 2011 at 16:12 baikbaik 1,0132 gold badges15 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

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

More info:

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

本文标签: javascriptjQuery global regex for replace with variableStack Overflow