innerText.includes() 去除换行符

问题描述 投票:0回答:1

我正在为 Lojban 制作一个字典网站。它相对简单:加载预制的

<div id="entries">
并将包含搜索查询的
innerText
的所有条目移动到
div#results

问题

没有包含字符串

u.a
的条目,但存在一个结果,其
innerText
包含
u\n\na
innerText
中的
search(query)
似乎正在删除换行符,尽管(a)它不应该这样做(b)运行
document.querySelector("#results .entry").innerText.includes("u.a")
返回
false

尝试修复

.replaceAll(/\n+g/, " ")
上运行
innerText
,然后在其中找到搜索查询

相关代码

const id = (x) => document.getElementById(x);
function search(query) {
    var i = 0;
    var results = [];
    for (const entry of id("entries").childNodes) {
        const text = entry.innerText.replaceAll(/\n+/g, " ");
        if (text.includes(query)) {
            console.log(text, query, text.includes(query));
            results.push(entry);
            i++;
        }
    }
    return [i, results];
}
// ... lazy-loading function ...
var timer;
id("search").addEventListener("input", function() {
    clearTimeout(timer);
    id("status").innerHTML = "<span>.....</span>";
    const q = id("search").value;
    let page = 0;
    if (observer) {
        observer.disconnect();
    }
    timer = setTimeout(function() {
        if (q.length != 0) {
            const s = search(q);
            const l = String(s[0]);
            const res = s[1];
            const pad = "<span>" + "0".repeat(5 - l.length) + "</span>";
            id("status").innerHTML = pad + l;
            id("results").innerHTML = "";
            // ... lazy-loading + url updating ...
        } else {
            id("status").innerHTML = "";
            id("results").innerHTML = "";
            page = 0;
        }
    }, 100);
});
javascript newline innertext
1个回答
0
投票

通过在我的数据库生成程序中添加一个空格字符解决了这个问题。哈哈

© www.soinside.com 2019 - 2024. All rights reserved.