javascript - 在现有脚本中包括使用正则表达式映射方法的 .replace 函数

标签 javascript html regex replace str-replace

我有以下脚本:

$(".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/

相关文章:

javascript - Modernizr 未检测到 Chrome 和 Firefox 中的功能

javascript - 在 JSF 应用程序中显示消息

javascript - Electron 存储 javascript 函数

javascript - 为什么要用%来计算hashCode索引转换?

javascript - 更新 html meteor ?

html - 使 css 组复选框独立工作

html - Nimbus Sans L 仅在 Firefox 中以上标呈现 TM ...浏览器错误?

regex - 检查字符串是否是有效的正则表达式模式 VB.NET

php - 如何在MySQL中按前两个和后两个字符搜索数据

java - 匹配正则表达式中最长的字符串或公共(public)子字符串的情况