JavaScript - 替换字符串中的方括号 [英] JavaScript - replace square brackets in a string
本文介绍了JavaScript - 替换字符串中的方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的字符串并试图将 [~sample] 转换为 @sample.例如:
I have a simple string and trying to convert [~sample] to @sample. For example:
var string = 'Completely engineer client-based strategic [~theme] areas before cross [~media] technology';
string.replace('[~', '@');
我已经尝试了上述解决方案,但它只转换了第一个,并且无法删除 ].
I have tried above solution but it only convert the first one and the ] can not be removed.
现在我学会了如何使用/g
now I learnt how to use /g
推荐答案
这个问题比简单地嵌套 .replace
[@
和 ] 要复杂一些
The issue is a bit more complicated than simply nesting .replace
[@
and ]
var string = 'Strategic [~theme] areas with cross [~media] technology [this is fine] ok?';
document.body.innerHTML = string.replace(/\[~([^\]]+)\]/g, '@$1');
([^\]]+)
确保捕获任何不是 ]
但由 [~
分隔的字符和 ]
,这在任何情况下都是一个更好的解决方案,可以防止像 [别惹我]
之类的文本被......搞砸.
The ([^\]]+)
makes sure to capture any character that is not an ]
but is delimited by [~
and ]
, which is a better solution in any case preventing text like [don't mess with me]
to be... messed.
RegExp 在这里
这篇关于JavaScript - 替换字符串中的方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文