Javascript-can I reference the variable of the regular expression itself in the js regular expression?

Source: Internet
Author: User
For example, in php, {code...} can be used to reference the first parameter in \ 1. Can this be used in js regular expressions? For example, in php

preg_prelace("/<([a-z]+)>(.+?)<\/\\1>/is", $text);

This can be used by me\\1To reference the first parameter. Can this be used in the regular expression of js?

Reply content:

For example, in php

preg_prelace("/<([a-z]+)>(.+?)<\/\\1>/is", $text);

This can be used by me\\1To reference the first parameter. Can this be used in the regular expression of js?

Use\nYou can, for example\1,\2, For example:

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

Of course.

/<([a-z]+)>(.+?)<\/\1>/.exec("xxx")

PS. Because it is not in a string, you do not need two backslashes.

Yes, but in JSString.replace(reg,newStr)You can directly use regular expressions, so you do not need to package them in strings.
1 2 n the nth substring in the regular expression. You can use $1 $2 $ n to specify the matched string content.
For example, replace the matched tag with an empty string:

var str = '

hello world

';str.replace(/<([a-z]+)>(.+)<\/\1>/i,'<$1> ');//

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.