我有.load(dictionary.txt)生成的任何数组vals_array
现在我想比较<p>
中文本换行的contenteditable div中的每个单词,如果匹配数组中的任何单词,它将把该单词包装在
以下是数组代码的文本:
var vals_array = [];
$.each(splitCntEditableTxt,function(key,val){
var nameFound = $.inArray(val.trim().toUpperCase(), dictionary);
if (nameFound === -1){
//alert(val + " No Match"); //DEBUG
} else {
//alert(val + " found in array"); //DEBUG
//$("#notes").append('<span class="OMG">'+val+'</span>');
vals_array.push(val);
}
});
这是我想用来比较过滤文本并从数组中逐个匹配的代码:
$('#notes').findText({query: vals_array}).each(function (){
//wrap matched word with <span>
});
问题是,<p>
中的文本有时会:, - - spacing,\ n \ r和其他非单词元素。那么,我如何首先过滤掉
中的文本,只留下纯文字,然后将它们与vals_array
数组进行比较,如果匹配则用?包装?
非常感谢〜!!!
答案 0 :(得分:0)
您可以使用String#replace
替换带有链接的字词。 replace
有两个参数:
这意味着我们可以:
textContent
的{{1}},<p>
/\w+/g
,<span>
的{{1}} 以下示例显示了这些步骤。它使用了一些现代的javascript功能,因此您可能需要将其转换为es5。此外,它不能很好地处理插入位置,因此您必须fix that yourself。 (目前,它只是将其放在内容的末尾)
示例中的<p>
替换了以下字词:innerHTML
,<p>
和foo
。您可以在代码段顶部的数组中添加其他字词。
bar
baz
// The array source you mentioned
const wordsToMatch = ["foo", "bar", "baz"];
// For quick lookups, we make a Set
const matchingDict = new Set(wordsToMatch);
// Check if a word is in the dictionary and possibly return
// a <span> element
const convertWord = word => matchingDict.has(word)
? `<span class="highlight">${word}</span>`
: word;
// Check the textContent of an event target for words in dictionary
// and update accordingly
const handleChange = e => {
e.target.innerHTML = e.target.textContent
.replace(/\w+/g, convertWord);
setRangeToEnd(e.target);
};
// Attach the logic to the contenteditable <p>
document
.querySelector("p")
.addEventListener("input", delay(300, handleChange));
// A utility to only run our text-adaptations x ms after the last change
function delay(dt, fn) {
let to = null;
return e => {
clearTimeout(to);
to = setTimeout(() => fn(e), dt);
}
}
function setRangeToEnd(target) {
const sel = window.getSelection();
const range = document.createRange();
range.selectNodeContents(target);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}