Regex 使用正则表达式或替换字符

Regex 使用正则表达式或替换字符,regex,Regex,我有一个正则表达式,它正在搜索空格或下划线的实例,用破折号替换它 function spinalCase(str) { var origSentence = str; // case of camelCase origSentence = origSentence.replace(/([a-z])([A-Z])/g, '$1 $2'); // convert to lower case and remove whitespace or underscores for dashes ori

我有一个正则表达式,它正在搜索空格或下划线的实例,用破折号替换它

function spinalCase(str) {

var origSentence = str;

// case of camelCase
origSentence = origSentence.replace(/([a-z])([A-Z])/g, '$1 $2');


// convert to lower case and remove whitespace or underscores for dashes
origSentence = origSentence.toLowerCase().replace(/ /g,"-");


return origSentence;
}


spinalCase('The_Andy_Griffith_Show');
我不知道如何在//g后面的正则表达式中添加逻辑“OR”,或者是否需要将其添加到“if”语句中,这看起来既笨重又笨拙。
感谢您的帮助

使用
|
或字符类:

.replace(/ |_/g,"-");
.replace(/[ _]/g,"-");
字符类将匹配列出的任何内容。除少数元字符外,几乎所有字符都将被视为文字字符,例如开始时的
^
将否定匹配(除了…)和
a-b
将在
a
b
之间进行更改

也许我错过了更多

|
是最接近逻辑or的<代码>匹配1 |匹配2

结合起来(我假设我们都是成年人,我不需要告诉你,实际上这样做是不好的做法):

哪一个匹配:

Johnson
Johnsen
Thomson
Thomsen
Johnson
Johnsen
Thomson
Thomsen