Javascript-如何突出显示与 HTML 中的表单用户输入文本区域匹配的元素数组

标签 javascript jquery html arrays highlight

对不起,我现在不知道怎么问清楚,我们有如下元素数组:

[' 64 dollars ', ' $6k billion ', ' 7 million'] 

用户输入类似“我有 64 美元,我兄弟有 6000 亿美元是 700 万美元”的文本

在 HTML 页面中,它需要显示 TEXTAREA 值以及突出显示的匹配数组元素。我尝试了很多像 RegEx、String 方法。

请建议我执行此操作的代码。

最佳答案

假设您的意思是along with highlighted matched array,而不是文本在文本区域内突出显示,那么此代码将起作用。

var arr = [' 64 dollars ', ' \\$6k billion ', ' 7 million']; // notice the double escape
var str = $("#x").val();
var re = new RegExp(arr.join("|"), "g"); // create a a | b | c regex
// console.log(re, str.match(re));
str.match(re).forEach(function(match, i) { // loop over the matches
  str = str.replace(match, function replace(match) { // wrap the found strings
    return '<em>' + match + '</em>';
  });
});
$("#output").html(str);
em { background-color:yellow }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


<textarea id="x">I have 64 dollars and my brother has $6k billion is 7 million</textarea>
<div id="output"></div>

关于Javascript-如何突出显示与 HTML 中的表单用户输入文本区域匹配的元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203533/

相关文章:

javascript - 使 div 根据 Javascript 值出现

javascript - 循环内的 onChange 事件仅传递第 0 个索引

javascript - 当用户观看 mp4 视频时设置在线用户

javascript - 用函数调用 jQuery 有什么作用?

javascript - 单击图像调整图像大小

JavaScript 和 Node.js RESTful Web 应用程序

javascript - 查找文本区域中光标的位置

jquery - 使用 jquery 解析 JSON

javascript - MMO 3D 游戏在 HTML5/WebGL 上的可行性

css - 可能以某种方式覆盖容器的填充?