简体   繁体   中英

how to highlight part of textarea html code

I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight match values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com ,but i was a newbie on js,i didn't understand his code meaning. any advice is appreciated

替代文字

To save time you should consider using an existing library for this requirement.

Quote from here :

As textarea elements can't render HTML, this plugin allows you to highlight text inside textarea elements.

jQuery highlightTextarea .

Demo: Codepen

Usage:

$context.highlightTextarea(options);

There is a pre element over the textarea. So when you type anything it is copying the input on the pre element, applying some filters.

For example:

<pre id="view"></pre>
<textarea id="code"></textarea>

When you type on #code it is copying the value, applying filters and adding the HTML to the #view .

var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
    val = this.value;
    val = YourRegex(val);
    (pre).innerHTML = val;
};

YourRegex would be a method to match the regex and return some parsed content to the pre , allowing you to customize the appearance of the textarea (that is actually an element over it).

function YourRegex(val)
{
    // This function add colors, bold, whatever you want.
    if (/bbcc/i.test("bbcc"))
        return "<b>" + val + "</b>";
}

@BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:

http://garysieling.github.io/jquery-highlighttextarea/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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