如何正确使用Javascript String.replace()方法?

时间:2017-10-16 15:58:31

标签: javascript jquery html angularjs

我有以下HTML标记和一些虚拟文本:

<p style="padding: 3%; border:1px solid black" id="myspan" ng-model="myspan" ng-mouseup="showSelectedText()">
    And so our resident genius, our Dr. Jekyll, explosively completed his transformation into Mr. Hyde.
    He declared this in front of the product design team, developers, management, and pre-launch customers. One of our project sponsors had the temerity to ask when the problem crippling our product would be fixed.
    Genius is a fickle beast. Sometimes you have the good fortune to work with a mad genius. Other times you are doomed to work with pure madness. There are also times when it is hard to tell the difference.
    This story is about the fall from grace of an extremely gifted team member with a deep understanding of our product’s architecture. He had an uncanny ability to forecast future requirements, and a ton of domain-specific knowledge.
    He was our top contributor. He was killing our flagship project.
</p>

    <input type="text" id="myword" value="{$ item $}">
    <input type ="button" value = "Highlight" ng-click="highlight($index, item)">

Javascript代码是:

    $scope.highlight = function(index, sentword) {
    var text = document.getElementById("myspan").innerHTML;
    if (sentword != '') {
            word = sentword;  // must be in brackets
            var re = new RegExp(word, "gi"); // ignore case, global change
            document.getElementById("myspan").innerHTML = text.replace(sentword, "<mark>"+sentword+"</mark>" );
        }
    };

这应该做的是突出显示发送到Javascript函数的单词。这通常与短句一致,例如以下文字: And so our resident genius, our Dr. Jekyll, explosively completed his transformation into Mr. Hyde.正确地附加了<mark>代码,然而,在句号结尾处带有额外空格的相同句子:And so our resident genius, our Dr. Jekyll, explosively completed his transformation into Mr. Hyde. *space*未正确附加<mark>代码。

这是我不理解的,因为较短的句子被正确替换,但是发送到Javascript函数的长句子不会被替换。

1 个答案:

答案 0 :(得分:1)

我认为你的问题是尾随的空白。为这两种情况生成的RegExp是不同的:

var a = RegExp("Hello World", "gi");
var b = RegExp("Hello World ", "gi"); //look trailing whitespace

String(a) == String(b) //false

您必须使用trim来清除空白。

var a = RegExp("Hello World", "gi");
var b = RegExp("Hello World ".trim(), "gi"); //look trailing whitespace

String(a) == String(b) //true

更新1

考虑两个人的想法:

  • 换行符未匹配。尝试从文本中删除它们或在highlight函数
  • 中实现更多逻辑
  • 以前突出显示的文字不匹配。检查regex生成vs innerHtml。也许您想在突出显示文本之前删除mark标记。