我有一个函数,它接受一个字符串(特别是来自输入的地址或邮政编码),然后在匹配的结果周围添加强标记。它工作正常,但我希望它能够匹配没有空格的字符。例如,如果输入字符串是 cf142
,我希望它匹配 CF14 2
。
下面是函数:
emboldenMatch(string, query) {
query = query.toLowerCase().trim();
if (string.toLowerCase().includes(query)) {
const queryLength = query.length;
const matchIndex = string.toLowerCase().indexOf(query);
const matchEnd = matchIndex + queryLength;
const before = string.substr(0, matchIndex);
const match = string.substr(matchIndex, queryLength);
const after = string.substr(matchEnd, string.length - matchEnd);
return `${before}<strong>${match}</strong>${after}`;
} else {
return string;
}
}
最佳答案
首先,您可以编写您的现有函数,如下所示:
function emboldenMatch(string, query) {
return string.replace(query, "<strong>$&</strong>")
}
console.log(em('some string with bold text', 'bold'));
如果您想要包装每个匹配项,而不仅仅是第一个匹配项,并且不敏感,您可以将其设为 regexp
,并添加 g
(=global ) 标志和 i
(=不敏感)标志:
function emboldenMatch(string, query) {
return string.replace(new RegExp(escapeRegExp(query), 'gi'), "<strong>$&</strong>")
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
console.log(emboldenMatch('some string with bold bold text', 'bold'));
现在,如果您想在字符之间添加可选空格,可以将其添加到正则表达式中,如下所示:
function emboldenMatch(string, query) {
var reg = new RegExp(escapeRegExp(query).split('').join('\\s*'), 'gi');
return string.replace(reg, "<strong>$&</strong>")
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
console.log(emboldenMatch('some string with bo ld b old text', 'bold'));
关于JavaScript include() 并忽略空白,修复代码格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61076095/