pattern matchin using javascript doesnt wrk when special characters and numbers come in between

后端 未结 1 1748
無奈伤痛
無奈伤痛 2021-01-28 07:50

I am trying to create a pattern matching to find word contents in an article for my website.. I am unable to make the pattern matchings when a special character or a number come

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 08:02

    I think the problem has to do with the boundaries you choose for your words, I believe that with \b you are not taking into account the case where the word is has a dot before (like ".cancer9". But I'm really not an expert in regex... so, I worked a little bit and got this solution, but I'm not sure if it will work for you:

    Javascript:

    $(document).ready(function () {
      var $test = $('#article');
      var entityText = $('#entity').html().replace(/\./g, "\\\.").replace(/\$/g, "\\\$").replace(/\?/g, "\\\?"); //etc...
      var entityRegularExpression =new RegExp("([^a-zA-Z0-9])(" + entityText + ")([^a-zA-Z0-9])", "gi");
      var highlight = '$1$2$3';
      $test.html($test.html().replace(entityRegularExpression, highlight));
    });
    

    And here you have a working demo: http://jsfiddle.net/ehzPQ/20/

    Let me know if it works for you.

    0 讨论(0)
提交回复
热议问题