当用户在搜索框中键入内容时,我试图突出显示网页上的某些文本。我的搜索算法只是匹配每个空格分隔的关键字。在我开始为我的搜索词添加括号之前,我认为这个功能是完美的。那踢了 SyntaxError:无效的正则表达式:****:未终止的组” 因为它被正则表达式解释了。我试图转义括号和其他字符,但突出显示不起作用。
https://codepen.io/anon/pen/YOaYEv
highlight (str) {
// this line works but prevents highlighting multiple keywords that arent connected
// var replacedStr = (this.search || '').replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')
// you can comment this line and uncomment above to see a different but not perfect option
var replacedStr = (this.search || '').replace(/ /g, '|')
return str.replace(new RegExp(replacedStr, 'gi'), match => {
return '<span class="font-weight-bold">' + match + '</span>'
})
}
所以我需要转义括号。我在注释行中尝试过,但是该函数无法突出显示文本中的所有关键字:/
有什么想法吗?
最佳答案
您需要转义要搜索和突出显示的每个非空白 block 。此外,无需在 replace
中使用回调。要替换为整个匹配项,您可以使用 $&
反向引用。
参见 updated JS :
vm = new Vue({
el: "#app",
data() {
return {
search: null,
message: 'Search this text for matches (check the bracketed area too)'
};
},
computed: {},
methods: {
highlight (str) {
var replacedStr = (this.search || '').trim().split(/\s+/).map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')).join("|");
return str.replace(new RegExp(replacedStr, 'gi'),
'<span class="teal--text text--darken-1 font-weight-bold">$&</span>');
}
}
});
这里:
-
.trim().split(/\s+/).map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&')).join("|")
- 用trim()
trim 输入字符串, 然后用.split(/\s+/)
拆分出所有非空白 block , 然后这些 block 用.map(x => x.replace(/[-[\]{}()*+!<=:?.\\^$|#\s,]/g, '\\$&'))
转义, 然后.join("|")
创建一个带有替代列表的正则表达式模式。 - 在
'<span class="teal--text text--darken-1 font-weight-bold">$&</span>'
字符串替换模式,$&
部分代表整个匹配值。
关于javascript - 转义 javascript 中的正则表达式特殊字符,但仍保留匹配关键字的字符串完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283522/