gpt4 book ai didi

javascript - 用jquery替换html页面中的单词或单词中的某些字符

转载 作者:行者123 更新时间:2023-11-28 02:19:18 24 4
gpt4 key购买 nike

我发现jquery代码(我忘记了原来的站点)正在努力将html页面中的一个单词替换为星号(*),并且代码运行良好,但是该代码只能用于替换每个单个单词,不能更改单词的部分且区分大小写。

JQuery 代码:

String.prototype.repeat = function(num){
return new Array(num + 1).join(this);
}

/* Word or Character to be replace */
var filter = ['itch','asshole', 'uck', 'sex'];
$('body').text(function(i, txt){
// iterate over all words
for(var i=0; i<filter.length; i++){
// Create a regular expression and make it global
var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');
// Create a new string filled with '*'
var replacement = '*'.repeat(filter[i].length);
txt = txt.replace(pattern, replacement);
}
// returning txt will set the new text value for the current element
return txt;
});

单词过滤器:

 ['itch','asshole', 'uck', 'sex'];

结果:

sex -> ***    // successfully replacing
SEX -> SEX // not replaced, i want this word also replaced to ***
bitch -> bitch // not replaced, i want this word replaced to b****

如何修改此jquery代码,以便可以用来更改单词中的某些字符并且不区分大小写?

fiddle :http://jsfiddle.net/bGhq8/

谢谢。

最佳答案

使用区分大小写的选项,无需边界。

String.prototype.repeat = function(num){
return new Array(num + 1).join(this);
}

/* Word or Character to be replace */
var filter = ['itch','asshole', 'uck', 'sex'];
$('body').text(function(i, txt){
// iterate over all words
for(var i=0; i<filter.length; i++){
// Create a regular expression and make it global

var pattern = new RegExp(filter[i] , 'gi'); // Add the "i" modifier for case insensitivity
// Create a new string filled with '*'
var replacement = '*'.repeat(filter[i].length);
txt = txt.replace(pattern, replacement);
}
// returning txt will set the new text value for the current element
return txt;
});

更新了 fiddle : http://jsfiddle.net/bGhq8/3/

关于javascript - 用jquery替换html页面中的单词或单词中的某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15915636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com