如何使用javascript突出显示textarea中搜索和替换的文本? [英] How to highlight the searched and replaced text in textarea using javascript?

查看:336
本文介绍了如何使用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>


这篇关于如何使用javascript突出显示textarea中搜索和替换的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆