简体   繁体   中英

replace string with square brackets

I wanted to replace the string including '?'and '[text]'. I tried with all the options, but not working. Those are special characters. How can we handle these ones.

src = src.replace('text=?', 'textNew=?');
src = src.replace('[text]', 'textNew');

Solution using RegExp object (Regular Expression implementation)

var a = "text=?othertext"
var b ="[text]othertext"
var r1= new RegExp("text=\\\?","g");
var r2= new RegExp("\\\[text\\\]","g");

var a_replaced = a.replace(r1,"textNew=?")
var b_replaced = b.replace(r2,"textNew")

? and [ and ] are special characters in RegExp. You have to escape them with triple \\ .

the g option in RegExp call, replace ALL the occurences of the substring in the string

https://regex101.com/ a service to test regular expression (adapted for various language)

https://www.w3schools.com/jsref/jsref_obj_regexp.asp the W3C documentation

You can use Regex for Replacing special Characters

src = src.replace(/\[text\]/,'textNew');
src = src.replace(/text=\?/,"textNew=?");

here \\ is used to allow Special Characters in string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM