Tips for using the character replacement function String. replace () in js

Source: Internet
Author: User

String. replace ()
Syntax:
Var strings = string. replace (regexp, replacement)

Regexp: the regular expression of the replacement operation. If a string is input, it is processed as a normal character and only one replacement operation is performed. If it is a regular expression, with the global (g) modifier, all target characters will be replaced. Otherwise, only one replacement operation will be performed.
Replacement: the character you want to replace.
The return value is the string after the replacement operation is executed.

11 String. replace () simple usage
Var text = "javascript is very powerful! "; 13 text. replace (/javascript/I," JavaScript "); 14 // return: JavaScript is very powerful!

String. replace () replace all Target Characters
Var text = "javascript is very powerful! JAVASCRIPT is my favorite language! "; 17 text. replace (/javascript/ig," JavaScript "); 18 // return: JavaScript is very powerful! JavaScript is my favorite language!

String. replace ()

Var name = "Doe, John ";
Name. replace (/(\ w +) \ s *, \ s * (\ w +)/, "$2 $1 ");
// Return value: John Doe

String. replace () is used to replace all characters in double quotation marks with characters in brackets.
Var text = '"JavaScript" is very powerful! '; 25 text. replace (/"([^"] *) "/g," [$1] "); 26 // return: [JavaScript] Very powerful!

String. replace () uppercase letters
Var text = 'a journey of a thousand miles begins with single step. '; 29 text. replace (/\ B \ w + \ B/g, function (word) {30 return word. substring (0, 1 ). toUpperCase () + 31 word. substring (1); 32}); 33 34 // return: A Journey Of A Thousand Miles Begins With Single Step.

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.