【问题标题】:Get first occurrence of string between two string in Javascript在Javascript中获取两个字符串之间第一次出现的字符串
【发布时间】:2015-07-09 09:04:35
【问题描述】:

我需要在Javascript中找到两个字符串之间第一次出现的字符串,这是我的字符串的一个例子:

"$$ hi my name is Mark $$"

我想获取 $$ 之间的文本,我该怎么做?

【问题讨论】:

    标签: javascript string


    【解决方案1】:

    你可以关注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);

    正则表达式解释

    1. /regex 的分隔符
    2. \$:匹配$字面量(需要使用\转义)
    3. ():抓捕组
    4. .*?: 匹配任意字符串

    【讨论】:

    • 在他的答案中使用 Magus 的 match 和 exec 有什么区别?
    • @Piero stackoverflow.com/questions/9214754/… 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.
    • 我注意到如果 myStr 不包含 $$ 分隔符会给我一个错误“null 不是评估...的对象”我该如何解决?
    • 现在给我这个错误:'null 不是评估'matches.length'的对象
    • 如何获得最后一次出现?
    【解决方案2】:

    你可以使用正则表达式:

    var mys = /\$\$(.*)\$\$/.exec('$$ hi my name is Mark $$')[1]
    

    【讨论】:

    • 为什么在string 中使用",不需要
    【解决方案3】:

    您可以使用正则表达式来做到这一点。 由于您只想要第一场比赛,请确保使用非贪婪。

    var yourVariable = "$$ hi my name is Mark $$ more stuff $$";
    var match = yourVariable.match(/\$\$(.*?)\$\$/)[1];
    alert(match);

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多