在现有脚本中包括使用正则表达式映射方法的 .replace 函数
including .replace function with regex map approach in existing script
我有以下脚本:
$(".balkenclosed").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
我尝试像这样添加一个 .replace 函数:
var replace = new Map([
/ [^a-zA-Z0-9\s]/ig, "", $id
]),
id = a;
replace.forEach(function(value, key){
id = id.replace(key, value);
});
它应该像这样替换 div 的 id 中的无效字符:
<div class="balken"><div class="balkenopen"><a id="2our$ / team/2$"
style="text-decoration:none; color:black;" href="#2our$ / team/2$">
our team</a></div></div>
这种情况下的结果应该是 id:"our_team" 和 href:"our_team"
我的方法行不通,我觉得我完全错了。
我真的很感激任何正确方向的提示
使用 value
作为正则表达式
var replace = [
/[^a-zA-Z0-9\s]/ig, ""
];
replace.forEach(function(value, key){
id = id.replace( value, "");
});
其实看replace的内容,简直
id = id.replace( replace[0], replace[1]);
我已经写了jquery,它会产生你想要的结果,你可以改进。希望对您有所帮助。
Please consider that it will search for entire anchor tag and replace if matches found. Replace $(a)
with the more appropriate selector for the specific search.
$('a').each(function() {
var self = $(this);
var id = self.attr('id');
var href = self.attr('href');
if (id)
self.attr('id', stripEverything(id, '_'));
if (href)
self.attr('href', '#'+stripEverything(href, '_'));
});
function stripEverything(string, replaceSpaceWith) {
return string.replace(/[^a-zA-Z ]+/g, '').split(' ').filter(function(e) {
return e
}).join(replaceSpaceWith);
}
您可以在 Fiddle
查看解决方案
我有以下脚本:
$(".balkenclosed").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
我尝试像这样添加一个 .replace 函数:
var replace = new Map([
/ [^a-zA-Z0-9\s]/ig, "", $id
]),
id = a;
replace.forEach(function(value, key){
id = id.replace(key, value);
});
它应该像这样替换 div 的 id 中的无效字符:
<div class="balken"><div class="balkenopen"><a id="2our$ / team/2$"
style="text-decoration:none; color:black;" href="#2our$ / team/2$">
our team</a></div></div>
这种情况下的结果应该是 id:"our_team" 和 href:"our_team"
我的方法行不通,我觉得我完全错了。 我真的很感激任何正确方向的提示
使用 value
作为正则表达式
var replace = [
/[^a-zA-Z0-9\s]/ig, ""
];
replace.forEach(function(value, key){
id = id.replace( value, "");
});
其实看replace的内容,简直
id = id.replace( replace[0], replace[1]);
我已经写了jquery,它会产生你想要的结果,你可以改进。希望对您有所帮助。
Please consider that it will search for entire anchor tag and replace if matches found. Replace
$(a)
with the more appropriate selector for the specific search.
$('a').each(function() {
var self = $(this);
var id = self.attr('id');
var href = self.attr('href');
if (id)
self.attr('id', stripEverything(id, '_'));
if (href)
self.attr('href', '#'+stripEverything(href, '_'));
});
function stripEverything(string, replaceSpaceWith) {
return string.replace(/[^a-zA-Z ]+/g, '').split(' ').filter(function(e) {
return e
}).join(replaceSpaceWith);
}
您可以在 Fiddle
查看解决方案