Reputation: 21
I have a string in which I want to replace an occurence which I am not being able to achieve following is the code
var code="user_1/has some text and user_1? also has some text";
newcode=code.replace(/user_1//g,'_');
One more thing if i have to replace a string from another string how to do? example.
var replacestring="user_1";
var code="user_1/some value here for some user";
var newcode=code.replace(/+replacestring+/g,'_');
Upvotes: 1
Views: 87
Reputation: 79830
Escape the /
in the regex using \
newcode=code.replace(/user_1\//g,'_');
For your comment
@Vega I have another confusion. can i use a value in a string to pass instead of user_1/ for replacement? what would be the syntax?
You can initialize RegEx object like below,
var userName = 'user_1/';
var newcode = code.replace(new RegExp(userName, 'g'), '_');
Upvotes: 1
Reputation: 150253
/
is a special char thus needs to be escaped with \
before it:
var code = "user_1/has some text and user_1? also has some text";
var newcode = code.replace(/user_1\//g, '_');
alert(newcode);
if you want to replace all user_1
, use this:
var code = "user_1/has some text and user_1? also has some text";
var newcode = code.replace(/user_1/g, '_');
alert(newcode);
Upvotes: 1