【问题标题】:jQuery regex to find string by substringjQuery 正则表达式通过子字符串查找字符串
【发布时间】:2017-07-04 09:58:27
【问题描述】:

在我的网站上,我有多次出现的字符串总是具有相同的子字符串(比如说“boo-foo”、“loo-foo”和“great-foo”)。

我想用 firstpart-foo 替换所有这些。 所以所有这些的第一部分应该是粗体。

谁能在 jQuery 中提供一个正则表达式?

我相信它应该看起来像这样,但使用正则表达式:

$(this).html($(this).html.replace("boo-foo","<strong>boo-</strong>foo"));

【问题讨论】:

    标签: javascript jquery regex web replace


    【解决方案1】:
    $(this).html($(this).html().replace(/^(.*)\-foo$/ig,'<strong>$1</strong>-foo');
    

    【讨论】:

      【解决方案2】:

      请检查此脚本,

      var htmlText = $('body').html();
      var replaced = htmlText.replace(/([\w\d]+)\-foo/ig, "<strong>$1</strong>-foo");
      $('body').html(replaced);
      

      小提琴:https://jsfiddle.net/o6doa4o6/

      更新了 Fiddle 以使“-”也加粗。

      https://jsfiddle.net/o6doa4o6/1/

      【讨论】:

        【解决方案3】:

        您可以使用 back Reference 查找捕获的组,然后使用 string.replace 方法使用 Regex 替换字符串。反向引用允许引用先前由捕获组匹配的文本。在 javascript 中,您可以使用 $1 来引用第一个捕获的组。同样$2, $3.. 用于每个捕获的组。

        以下实现显示了此行为,不包括 Jquery 部分。

        var stringValue = `boo-foo
        loo-foo
        great-foo`;
        
        var regexToSearch = /([a-zA-Z]*)-foo/g;
        
        var result = stringValue.replace(regexToSearch, '<strong>$1</strong>-foo');
        console.log(result);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-05-16
          • 2012-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多