方法

使用括号的子字符串匹配

下面的脚本使用replace()方法来转换字符串中的单词。在匹配到的替换文本中,脚本使用替代的$ 1,$ 2表示第一个和第二个括号的子字符串匹配。

  1. var re = /(\w+)\s(\w+)/;
  2. var str = "John Smith";
  3. var newstr = str.replace(re, "$2, $1");
  4. console.log(newstr); // "Smith, John"

指定一个函数作为参数

MDN

  1. function replacer(match, p1, p2, p3, offset, string) {
  2. // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  3. return [p1, p2, p3].join(' - ');
  4. }
  5. var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
  6. console.log(newString); // abc - 12345 - #$*%

中文字符

匹配中文标点符号:
\u3002——。
\uff1b——;
\uff0c——,
\uff1a——:
\u201c——“
\u201d——”
\uff08——(
\uff09——)
\u3001——、
\uff1f——?
\u300a——《
\u300b——》
所有中文——[\u4e00-\u9fa5]
image.png

URL查询参数

  1. reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");

不包含某个字符串

难度大,目前还没理解

  1. /^((?!hede).)*$/s

stackflow权威回答
翻译文章

注意点

reg.test()时,慎重全局查找/…/g属性