如何用正则表达式替换不同的字符并添加条件.

Tay*_*tin -1 javascript regex

示例字符串: George's - super duper (Computer)

想要新的字符串: georges-super-duper-computer

目前的正则表达式: .replace(/\s+|'|()/g, '-')

它不起作用,并且当我删除空格并且-之间已经有一个类似的东西george's---super.

小智 5

tl; dr你的正则表达式是畸形的.你也不能有条件删除',并\s ( )在一个单一的表达.


你的正则表达式是不正确的,因为()具有特殊含义.它们用于组成组,因此您必须将它们作为\(和组件进行转义\).你还必须|在它们之间放置另一个管道,否则你将匹配文字"()",这不是你想要的.

正确的表达方式如下:.replace(/\s+|'|\(|\)/g, '-').

但是,这不是你想要的.因为这会产生George-s---super-duper--Computer-.我建议您使用字符类,这也将使您的表达更容易阅读:

.replace(/[\s'()-]+/g, '-')

这符合空白,',(,)以及任何额外的-或更多的时间,并与替换它们-,高产George-s-super-duper-Computer-.

这仍然不太正确,所以有这个:

var myString = "George's - super duper (Computer)";

var myOtherString = myString
  // Remove non-whitespace, non-alphanumeric characters from the string (note: ^ inverses the character class)
  // also trim any whitespace from the beginning and end of the string (so we don't end up with hyphens at the start and end of the string)
  .replace(/^\s+|[^\s\w]+|\s+$/g, "")

  // Replace the remaining whitespace with hyphens
  .replace(/\s+/g, "-")

  // Finally make all characters lower case
  .toLowerCase();

console.log(myString, '=>', myOtherString);
Run Code Online (Sandbox Code Playgroud)