Jquery - 在字符串中查找单词并用<span>标记包装它

时间:2016-07-14 14:00:56

标签: javascript jquery string indexof

我需要编写一个函数,将一个单词作为arg,在一个字符串中找到它,并仅用jquery / js突出显示该单词。

jsfiddle.net/xzh2qmcd/ 

我已经得到了这个词,并在这里得到了indexOf,但我不知道如何只在这个词出现的地方添加span标签。

任何帮助我们都很棒,我在这里检查一些其他问题并且无法理解我应该做些什么。

3 个答案:

答案 0 :(得分:1)

你需要这样做:

    var txt = textDiv.replace(new RegExp(searchInput, 'gi'), function(str) {
      return "<span class='highlight'>" + str + "</span>"
    });

var txt = textDiv.replace(
                  new RegExp(searchInput, 'gi'), 
                  "<span class='highlight'>$&</span>");

gi ->所有不区分大小写的匹配文字

$(document).ready(function() {
  // globals
  var searchInput;
  var textDiv;

  $('.searchBtn').click(function(event) {

    event.preventDefault();

    // set the values of the search and the text
    searchInput = $('.searchInput').val();
    textDiv = $('.textDiv').text();
    var reg = new RegExp(searchInput, 'gi');
    var txt = textDiv.replace(reg, function(str) {
      return "<span class='highlight'>" + str + "</span>"
    });
    $('.textDiv').html(txt);
  });
});
.textDiv {
  height: 100px;
  width: 500px;
  text-align: center;
  padding: 20px;
  margin: 0 auto;
}

.highlight {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="main">
    <div class="searchDiv">
      <h3> Mask A Word In The Text: </h3>
      <label>
        <input class="searchInput" type="text" value = "iS"/> </label>
      <button class="searchBtn" type="button"> Search </button>
    </div>

    <div class="textDiv">
      Bastille Day is the common name given in English-speaking countries to the French National Day, which is celebrated on 14 July each year. In France, it is formally called La fête nationale (French pronunciation: ​[la fɛːt nasjɔnal]; The National Celebration) IS Is
      and commonly Le quatorze juillet. (French pronunciation: ​[lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July).
    </div>
  </div>
</div>

答案 1 :(得分:0)

您可以使用以下代码实现所需。

我已更新我的答案以提供完整的单词匹配。我想你只会寻找那个。

示例:如果您搜索国家/地区,则不应该为国家/地区字添加颜色,如果您不进行全字搜索,则会发生这种情况。

// search for the input in the paragraph
      if (textDiv.toLowerCase().indexOf(searchInput.toLowerCase()) >= 0) {
         console.log("match");
         textDiv = textDiv.replace(new RegExp('\\b('+searchInput+')\\b', 'gi'),'<span class="highlight">$1</span>');


       $('.textDiv').html(textDiv);

小提琴:http://jsfiddle.net/xzh2qmcd/3/

答案 2 :(得分:0)

&#13;
&#13;
$(document).ready(function() {
   // globals
   var searchInput;
   var textDiv;

   $('.searchBtn').click(function(event) {

      event.preventDefault();

      // set the values of the search and the text
      searchInput = $('.searchInput').val();
      textOfDiv = $('.textDiv').text();

      // search for the input in the paragraph
      if (textOfDiv.indexOf(searchInput) >= 0) {
         console.log("match");
					var newText = textOfDiv.split(searchInput).join('<span class="highlight">' + searchInput + '</span>' );
$('.textDiv').html(newText);
}
      else {
         console.log("no match");
      }
   });
});
&#13;
.textDiv {
    height:100px;
    width:500px;
    text-align:center;
    padding:20px;
    margin:0 auto;
}

.highlight {
    background:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="main">
        <div class="searchDiv">
                    <h3> Mask A Word In The Text: </h3>
                    <label> <input class="searchInput" type="text" /> </label>
                    <button class="searchBtn" type="button"> Search </button>
        </div>

        <div class="textDiv">
                Bastille Day is the common name given in
                English-speaking countries to the French National Day,
                which is celebrated on 14 July each year. In France,
                it is formally called La fête nationale (French pronunciation: ​[la fɛːt nasjɔnal]; The National Celebration)
                and commonly Le quatorze juillet.
                (French pronunciation: ​[lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July).
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

&#13;
&#13;
$(document).ready(function() {
   // globals
   var searchInput;
   var textDiv;

   $('.searchBtn').click(function(event) {

      event.preventDefault();

      // set the values of the search and the text
      searchInput = $('.searchInput').val();
      textOfDiv = $('.textDiv').text();

      // search for the input in the paragraph
      if (textOfDiv.toLowerCase().indexOf(searchInput) >= 0) {
         console.log("match");
		  var newText = textOfDiv.split(searchInput).join('<span class="highlight">' + searchInput + '</span>' );
$('.textDiv').html(newText);
}
      else {
         console.log("no match");
      }
   });
});
&#13;
.textDiv {
    height:100px;
    width:500px;
    text-align:center;
    padding:20px;
    margin:0 auto;
}

.highlight {
    background:red;
}
&#13;
<div class="container">
    <div class="main">
        <div class="searchDiv">
                    <h3> Mask A Word In The Text: </h3>
                    <label> <input class="searchInput" type="text" /> </label>
                    <button class="searchBtn" type="button"> Search </button>
        </div>

        <div class="textDiv">
                Bastille Day is the common name given in
                English-speaking countries to the French National Day,
                which is celebrated on 14 July each year. In France,
                it is formally called La fête nationale (French pronunciation: ​[la fɛːt nasjɔnal]; The National Celebration)
                and commonly Le quatorze juillet.
                (French pronunciation: ​[lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July).
        </div>
    </div>
</div>
&#13;
&#13;
&#13;