如何使用javascript突出显示textarea中搜索和替换的文本?
问题描述:
我需要find和replace的功能。我可以替换并找到文本。但是不能突出显示textarea中的文本以及如何获取已发现文本的出现。如果它是第一次出现,突出显示的颜色应该与其他人不同。因此我需要在我的项目中。但是我是空白如何做到这一点。你能否回答代码如何实现它。
I need a functionality of find and replace.I could replace and find the text. But couldn't to highlight the text in textarea and also how to get the occurrences of found texts.If it is first occurrence,the highlighted color should be different from rest of others.As such I need in my project. But am blank how to do this.Can you please reply with the code how to achieve it.
答
replace()方法在字符串中搜索指定的值,或正则表达式,并返回一个替换指定值的新字符串。
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/blue/g, "red");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>