Javascript-我如何突出显示与表单中HTML用户输入文本区域匹配的元素数组 [英] Javascript-How Can i Highlight array of elements that matches with form User input textarea in HTML

查看:116
本文介绍了Javascript-我如何突出显示与表单中HTML用户输入文本区域匹配的元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Sorry,i dont now how to ask question clearly,We have Array of elements like following:

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

用户输入的文字为我有64美元,我的兄弟有60亿美元,就是700万"

User enters a text like "I have 64 dollars and my brother has $6k billion is 7 million"

在HTML页面中,它需要显示TEXTAREA值以及突出显示的匹配数组元素.我已经尝试了许多类似RegEx,String方法的方法.

In HTML page it needs to display the TEXTAREA value along with highlighted matched array elements. I've tried many like RegEx, String methods.

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

Please suggest me the code to do this.

推荐答案

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

Assuming you mean along with highlighted matched array and not that the text is highlighted INSIDE the textarea then this code will work.

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用户输入文本区域匹配的元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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