简体   繁体   English

Javascript正则表达式将括号替换为内部内容

[英]Javascript Regex to replace brackets with content inside

I'm trying to build a regular expression to replace brackets with other content, in this case, a div tag.. 我正在尝试构建正则表达式以将方括号替换为其他内容,在这种情况下为div标签。

So, the text: 因此,文本:

This is a [sample] text

Would become: 会成为:

This is a <div>sample</div> text

The problem is, it should only replace when both brackets are found, and keep the content inside. 问题是,仅当找到两个方括号时才应更换,并将其内容保留在里面。 If only one bracket is found, it should ignore it.. 如果仅找到一个括号,则应将其忽略。

So 所以

This is a [sample text

or 要么

This is a ] sample text

Both would remain as is. 两者都将保持原样。

Also it should match more than one occurence, so: 此外,它应匹配多个事件,因此:

This [is] a [sample] [text]

Would become 会成为

This <div>is</div> a <div>sample</div> <div>text</div>

And one last thing, it should remove (or at least ignore) nested brackets, so 最后一件事,它应该删除(或至少忽略)嵌套的括号,因此

This [[is a ] sample [[[ tag]]]

Would become 会成为

This <div>is a</div> sample <div> tag </div>

This is what I got until now: 这是我到目前为止所得到的:

function highlightWords(string){
    return string.replace(/(.*)\[+(.+)\]+(.*)/,"$1<div>$2</div>$3");
}

It works in simple cases, but won't get multiple occurences and won't remove other tags. 它可以在简单的情况下使用,但不会多次出现,也不会删除其他标签。 Any regex masters around? 是否有正则表达式高手?

No need to describe content before and after brackets. 无需在方括号之前和之后描述内容。 You must forbid brackets in the content description, so use [^\\][]+ instead of .+ . 您必须在内容描述中禁止使用方括号,因此请使用[^\\][]+而不是.+ Don't forget to add g for a global replacement: 不要忘记为全局替换添加g

function highlightWords(string){
    return string.replace(/\[+([^\][]+)]+/g,"<div>$1</div>");
}

Note: you don't need to escape the closing square bracket outside a character class, it isn't a special character. 注意:您无需在字符类外转义右方括号,因为它不是特殊字符。

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

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