简体   繁体   English

替换所有字符串出现

[英]Replace all string occurrences

I want to replace all the occurrences of [h2][/h2] in a JavaScript string For example, I have 我想在JavaScript字符串中替换所有[h2][/h2]的出现例如,我有

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

I want to get -> hii 我想得到 - > 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: 如果[h2]和[/ h2]也可以分开显示,你可以使用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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