2017-08-06 143 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));