替换Div中的所有管道字符

ans*_*rob 3 javascript regex jquery

我正在使用一个相当老的网站并使它具有响应能力。开发人员按如下所示设置“导航”,没有列表或其他内容。移动导航将是垂直的,我不希望“ |” 字符。我想做到这一点而无需触摸导航HTML或添加第二个菜单以在较小的屏幕上显示。

<div id="mainNav">
  <a href="/home">Home</a>|
  <a href="/about">About</a>|
  <a href="/areas-of-practice">Areas of Practice</a>|
  <a href="/in-the-news">In the News</a>|
  <a href="/contact">Contact</a>
</div>
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这行jQuery,但似乎删除了标签以及“ |”,只留下了“ HomeAboutAreas of PracticeIn the NewsContact”字符串。我如何只删除“ |” 并保持其他一切不变?

$('#mainNav').text(function(index,text){
  return text.replace(/[|]/g,'');
});
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

使用.html代替,.text以便保留HTML。

[]当您只替换一个字符时,也无需在正则表达式中使用。但是,您需要将管道字符转义到字符集之外,因为这意味着要进行替换。

$("#doit").click(function() {
  $('#mainNav').html(function(index, text) {
    return text.replace(/\|/g, '');
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainNav">
  <a href="/home">Home</a>|
  <a href="/about">About</a>|
  <a href="/areas-of-practice">Areas of Practice</a>|
  <a href="/in-the-news">In the News</a>|
  <a href="/contact">Contact</a>
</div>
<button id="doit">Remove pipes</button>
Run Code Online (Sandbox Code Playgroud)