简体   繁体   中英

Replace all string occurrences

I want to replace all the occurrences of [h2][/h2] in a JavaScript string For example, I have

var mystring = 'hii[h2][/h2]';

I want to get -> hii

so far I tried

mystring.replace(/[h2][\/h2]/g, "");

You need to escape the square braces.

 var mystring = 'hii[h2][/h2]'; let string = mystring.replace(/\\[h2\\]\\[\\/h2\\]/g, ''); console.log(string); 

假设这些标签之间没有任何内容,您还需要转义[]

mystring.replace(/\[h2]\[\/h2]/g, "");

try this one:

str.replace(/\[h2\]\[\/h2\]/g,"");

note that you have to escape [ and ] if they form part of the text you want to replace otherwise they are interpreted as "character class" markers.

If the [h2] and [/h2] could also appear separate, you could use this one:

str.replace(/\[\/?h2\]/g,"");

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