JavaScript Replace function

Source: Internet
Author: User

Defined

The replace () function is used for replacing strings.

Grammar
Stringobject.replace (Regexp/substr, newsubstr/function)

Parameters

REGEXP/SUBSTR Regular Expression/string

Newsubstr/function Replace text/Generate alternate text function


Example

var str = "Visit microsoft!"; var res = str.replace ("Microsoft", "W3Schools");

Replace character

What does it mean if the replacement string Newsubstr contains the $ character?

A text that matches the 1th to 99th sub-expression in the $, $, ..., $ $ and regexp

$& and regexp matching substring

$ ' text on the left side of the matching substring

$ ' text on the right side of the matching substring

$$ Direct volume symbol.


What is the meaning of the sub-expression mentioned in the above $, $ ... An expression enclosed in parentheses in a regular expression.

/a/No sub-expression

/[a]/No sub-expression

/(a)/have sub-expression (a)

/(a), (b)/have sub-expressions (a), (b)


Example

Name = "Doe, John"; Name.replace (/(\w+) \s*, \s* (\w+)/, "$ $");//output "John Doe"


Replace function

Replace function description

function (Match, p1, P2,..., offset, string)

Match matches to the string

P1, p2 ... Sub-expression to match

Offset matches the position of the string

String Entire string


Example

var name = "Ace:mm-abc". Replace (/([\:\-\_]+ (.))        /, function (Match, p1, P2, offset, total) {Console.log ("match:" + _);        Console.log ("P1:" + separator);        Console.log ("P2:" + letter);        Console.log ("offset:" + offset); Console.log ("total:" + All) return offset? P2.touppercase (): p2;}) Console.log (name)/* Output substr::m TEST.HTML:43P1::MP2:MOFFSET:3TOTAL:ACE:MM-ABCACEMM-ABC */

There are two sub-expressions in the above regular expression

P1 is a sub-expression ([\:\-\_]+ (.)) Match to the content ": M"

P2 is a child form (.) Match to the content "M"


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.