用下划线替换空格和符号

Replace spaces and ampersands with an underscore

我试图遍历一些变量并用下划线替换 space 或 & 的任何实例。我让它工作了 spaces,我将如何添加 & 呢?

$(function() {
  $('div').each(function() {
    var str = $(this).text(),
        str = str.replace(/\s+/g, '_').toLowerCase();
        
    console.log(str);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Testing</div>
<div>Testing This</div>
<div>Testing &amp; This</div>

检查这个:Regular Expressions,特别是看看 "character sets",你可以用它来写你的正则表达式:

str.replace(/[\s&]+/g, '_')

因此字符 class 内的任何内容都将被匹配,而不仅仅是空格。

请注意,此表达式是用单个下划线替换多次出现的 & 和空格,因此:

"hello&&&&&&&world"

变成:

"hello_world"

如果这不是您想要的,请不要使用 +:

str.replace(/[\s&]/g, '_')

所以 "hello&&&&&&&world" 变成:

"hello_______world"