简体   繁体   English

仅突出显示搜索中的第一个字符串

[英]highlighting only the First string in Search

I am new to JavaScript. 我是JavaScript新手。 I am facing a problem with my javascript code. 我的JavaScript代码面临问题。 I am trying to use the string replace method to highlight the searched text. 我正在尝试使用字符串替换方法来突出显示搜索到的文本。 But My function only highlight the First string that it find and dont highlight another strings !! 但是我的函数仅突出显示它找到的第一个字符串,而不突出显示另一个字符串! How can I fix it to find all strings that I type in search . 如何解决它以找到我在search中键入的所有字符串。 Here is my Code : 这是我的代码:

<html>
<head>
    <script language="javascript">
    function search()
    {
        var s = document.getElementById("p1").innerHTML
        document.getElementById("p1").innerHTML = s.replace(document.getElementById('txt').value , '<span style="color:red">'+document.getElementById("txt").value+'</span>')
    }
    </script>
</head>
<body>
    <input type="text" id="txt" value="search..." onfocus="value=''" />
    <input type="button" id="btn" value="search" onclick="search()"/>
    <p id="p1">
        Type any word from this paragraph in the box above, then click the "Search" button to highlight it red      
    </p>


</body>

Regular expression with g global flag will help: g 全局标志的正则表达式将有助于:

function search() {
    var p1 = document.getElementById("p1"),
        value = document.getElementById("txt").value,
        regex = new RegExp("\\b" + value + "\\b", "gi"),
        rwith = '<span style="color: red;">$&</span>';

    p1.innerHTML = p1.innerHTML.replace(regex, rwith);
}

DEMO: http://jsfiddle.net/guC4j/ 演示: http : //jsfiddle.net/guC4j/

One option is to use split and join like so: 一种选择是使用splitjoin如下所示:

document.getElementById("p1").innerHTML = s.split(document.getElementById('txt').value).join('<span style="color:red">'+document.getElementById("txt").value+'</span>');

Here's a jsFiddle to play with. 这是一个可玩的jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM