Javascript - 在方括号之间返回字符串 [英] Javascript - return string between square brackets
本文介绍了Javascript - 在方括号之间返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要只返回字符串中方括号内的文本。我有以下正则表达式,但这也返回方括号:
I need to return just the text contained within square brackets in a string. I have the following regex, but this also returns the square brackets:
var matched = mystring.match("\\[.*]");
一个字符串只包含一组方括号,例如:
A string will only ever contain one set of square brackets, e.g.:
Some text with [some important info]
我希望匹配包含'一些重要信息',而不是我目前得到的'[一些重要信息]。
I want matched to contain 'some important info', rather than the '[some important info]' I currently get.
推荐答案
使用分组。我添加了一个?
来匹配ungreedy,因为这可能是你想要的。
Use grouping. I've added a ?
to make the matching "ungreedy", as this is probably what you want.
var matches = mystring.match(/\[(.*?)\]/);
if (matches) {
var submatch = matches[1];
}
这篇关于Javascript - 在方括号之间返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文