About JS String function String. replace () _ basics-js tutorial

Source: Internet
Author: User
This article describes the JS String function String. replace (). For more information, see. Replace (one or more) substrings matching a given regular expression

String. replace (regexp, replacement)

Parameters:

Regexp: RegExp object or string

Replacement: replacement text string, or a function, used to generate the corresponding replacement text during the call.

Return Value:

Returns a new string.

Description:

Replacement can be a string or a function. If it is a function, it will be called on each matching result, and the string it returns will be used as the replacement text.

Parameters passed in the function:

1) string matching the pattern

2) match the string of A parentheses subexpression in this mode. It may be 0 or multiple such parameters.

3) an integer that specifies the position where the matching result appears in the String.

4) string itself

Example:

The Code is as follows:


// Make sure that the word "javascript" is in the correct case.
Text. replace (/javascript/I, 'javascript ');
// Replace all double quotation marks with the correct single quotation marks
Text. replace (/"([^"]) "/g," ''$1 ''");
// Convert a separate name from the format "Mack, Xu" to "Xu Mack"
Name. replace (/(\ w +) \ s *, \ s * (\ w +)/, "$2 $1 ");
// Capital the first letter of all words in a string
Text. replace (/\ B \ w + \ B/g, function (word ){
Return word. substring (0, 1). toUpperCase () + word. substring (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.