[英]Highlight matching text
当将用户文本发布到网页上时(使用Mongodb以及node和js),我试图突出显示与商店数组中的商店名称相匹配的任何文本。 用于遍历数据库并发布到页面的代码:
<% posts.forEach(function(post) { %>
<div class="post">
<h4 class="date">
<span><%= post.created.toDateString() %></span>
</h4>
<p class="post_text"><%- post.body %></p>
</div>
<% }); %>
我有一些练习js控制台代码,我曾经用来匹配数组中的单词,但是在将文本与突出显示的单词放回一起方面遇到困难。 2个字库名称是另一个问题...
var blogInput = "We went to target last night, also to publix";
var array1 = blogInput.split(" ");
var array2 = ["kroger", "lums", "marlows", "eats", "burger king",
"home", "wendys", "publix", "donut circus", "jewelry store",
"target"];
function getMatch(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ) {
var x = a[i];
matches.push( x );
}
}
}
return matches;
}
getMatch(array1, array2);
(2) ["target", "publix"]
然后,使用此示例,我想将字符串句子放回原处,并以蓝色显示“ target”和“ publix”文本的页面。 任何暗示或智慧之言都会有所帮助。 谢谢!
您不需要两个循环,只需将blogInput
作为字符串使用,而不是将其拆分为单个单词,然后使用indexOf
(或includes
)确定关键字是否在字符串中。 这也解决了尝试查找具有多个单词的商店名称的问题。
var blogInput = "We went to target last night, also to publix";
var array2 = ["kroger", "lums", "marlows", "eats", "burger king",
"home", "wendys", "publix", "donut circus", "jewelry store",
"target"];
// filter out any store names that aren't included in blogInput
var matches = array2.filter(function(store) {
return blogInput.indexOf(store) > -1;
});
您可能还需要blogInput.toLowerCase()
和store.toLowerCase()
来解决大小写问题。
如果您要针对支持ES6或使用Babel这样的编译器的新浏览器,则可以简化为:
const blogInput = "We went to target last night, also to publix";
const storeNames = ["kroger", "lums", "marlows", "eats", "burger king",
"home", "wendys", "publix", "donut circus", "jewelry store",
"target"];
// filter out any store names that aren't included in blogInput
var matches = storeNames.filter(store => blogInput.includes(store));
您将需要使用改变其颜色的特定类在span
突出显示突出显示的单词。
可以使用这些跨度重新构建帖子的功能可能与此类似。
let blogInput = "We went to target last night, also to publix";
let blogWords = blogInput.split(" ");
let searchedWords = ["kroger", "lums", "marlows", "eats", "burger king",
"home", "wendys", "publix", "donut circus", "jewelry store",
"target"];
function getMatch(a, b) { ... }
let matchedWords = getMatch(blogWords, searchedWords);
let blogText = '';
blogWords.forEach(function(word) {
if (matchedWords.indexOf(word) != -1) {
blogText += ' <span class="highlight">' + word + '</span>';
} else {
blogText += ' ' + word;
}
});
// Remove leading space
blogText = blogText.trim();
然后,您应该使用blogText
作为您的帖子文本。 您还需要添加类似于此规则的CSS规则:
span.highlight {
color: blue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.