2017-08-06 142 views
0

将用户文本发布到网页(使用Mongodb和节点以及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控制台的代码,但我有困难与把文字重新走到一起与突出显示的单词前进(S)。 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"] 

使用这个例子,然后我想将字符串句子重新走到一起,并发布到页面与“目标”和蓝色“域名后缀”文本。任何提示或智慧的话都会有帮助。谢谢!

回答

0

您需要围绕在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; 
} 
0

您不需要两个循环,只需使用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; 
}); 

您可能还需要​​和store.toLowerCase()解决问题外壳。

如果您正在瞄准新的浏览器浏览器ES6支持或使用类似通天一个transpiler可以简化为:

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));