我有以下脚本:
$(".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"
我的方法行不通,我觉得我完全错了。 我真的很感激任何指向正确方向的提示
最佳答案
我已经编写了 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 查看解决方案
关于javascript - 在现有脚本中包括使用正则表达式映射方法的 .replace 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170983/