直播正则表达突出显示

时间:2016-05-09 23:47:45

标签: javascript

我正在尝试使用JavaScript实时突出显示正则表达式匹配。与http://regexr.com/

等网站类似
<p id="haystack"> Sample text Sample Text Sample Text Sample Text </p>

    <form>
      <input id="needle" onkeyup="highlight('haystack')" onkeydown="highlight('haystack')" type="text" placeholder="Enter Pattern" autofocus>
    </form>


function highlight(e){

    var pattern = document.getElementById('needle');

    var consoleText = document.getElementById('haystack').innerHTML;

    consoleText = consoleText.replace(pattern.value,"replaced");

    document.getElementById('haystack').innerHTML = consoleText;

我是JavaScript的新手。我怎样才能达到预期的效果?

1 个答案:

答案 0 :(得分:0)

试试这个:

function highlight(container,what,spanClass) {
    var content = container.innerHTML,
        pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','g'),
        replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
        highlighted = content.replace(pattern,replaceWith);
    return (container.innerHTML = highlighted) !== content;
}

用法:

highlight(document.getElementById('content'),'hello','highlight');