【发布时间】:2015-07-09 09:04:35
【问题描述】:
我需要在Javascript中找到两个字符串之间第一次出现的字符串,这是我的字符串的一个例子:
"$$ hi my name is Mark $$"
我想获取 $$ 之间的文本,我该怎么做?
【问题讨论】:
标签: javascript string
我需要在Javascript中找到两个字符串之间第一次出现的字符串,这是我的字符串的一个例子:
"$$ hi my name is Mark $$"
我想获取 $$ 之间的文本,我该怎么做?
【问题讨论】:
标签: javascript string
你可以关注regex
var myStr = "$$ hi my name is Mark $$ And his name is John $$";
var matches = myStr.match(/\$\$(.*?)\$\$/);
var str = matches && matches.length ? matches[1] : '';
alert(str);
正则表达式解释
/:regex 的分隔符
\$:匹配$字面量(需要使用\转义)():抓捕组.*?: 匹配任意字符串【讨论】:
exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions.String.match does this for you and discards the subexpressions' results.
你可以使用正则表达式:
var mys = /\$\$(.*)\$\$/.exec('$$ hi my name is Mark $$')[1]
【讨论】:
string 中使用",不需要
您可以使用正则表达式来做到这一点。 由于您只想要第一场比赛,请确保使用非贪婪。
var yourVariable = "$$ hi my name is Mark $$ more stuff $$";
var match = yourVariable.match(/\$\$(.*?)\$\$/)[1];
alert(match);
【讨论】: