簡體   English   中英

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

[英]How do I use the Javascript String.replace() method correctly?

我有以下帶有一些虛擬文本的 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* And so our resident genius, our Dr. Jekyll, explosively completed his transformation into Mr. Hyde. *space*沒有正確附加<mark>標簽。

這是我不明白的,因為較短的句子會被正確替換,但發送到 Javascript 函數的長句子不會被替換。

我認為您的問題是尾隨空格。 兩種情況生成的 RegExp 是不同的:

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

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

您必須使用修剪來清理空格。

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

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

更新 1

考慮兩個想法:

  • 換行符不匹配。 嘗試從文本中刪除它們或在highlight功能中實現更多邏輯
  • 先前突出顯示的文本不匹配。 檢查生成的正則表達式與innerHtml。 也許您想在突出顯示文本之前刪除mark標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM