Home  >  Article  >  Backend Development  >  javascript - 在js的正则里面能引用正则本身的变量吗?

javascript - 在js的正则里面能引用正则本身的变量吗?

WBOY
WBOYOriginal
2016-06-06 20:43:091042browse

比如在php里面

<code class="lang-php">preg_prelace("/(.+?)/is", $text);
</code>

这个在我可以用\\1来引用第一个参数,在js的正则表达式里可以这么用吗?

回复内容:

比如在php里面

<code class="lang-php">preg_prelace("/(.+?)/is", $text);
</code>

这个在我可以用\\1来引用第一个参数,在js的正则表达式里可以这么用吗?

\n就可以了,比如\1\2,例子:

<code>var regexp = /(['"])[^'"]*\1/;
console.log(
  regexp.test("'1'"),
  regexp.test('"2"'),
  regexp.test('"3\'')
); /* true true false */
</code>

当然可以啊

<code>/(.+?)/.exec("<a>xxx</a>")
</code>

PS. 因为不是在字符串里,所以你不需要两个反斜线

可以的,不过JS里面String.replace(reg,newStr)可以直接使用正则字面量的,所以不用包在字符串里面。
1 2 n 在正则里面第几个子串;可以用 $1 $2 $n 指匹配到的字符串内容
比如,把匹配到的标签替换成空字符串:

<code>var str = '<p>hello world</p>';
str.replace(/(.+)/i,'$1>');
//<p></p></code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn