Javascript String.Replace's Magical Basics

Source: Internet
Author: User
String.Replace () Introduction
Grammar:
Copy Code code as follows:

String.Replace (RegExp, replacement)

RegExp: The regular expression for which you want to perform the substitution operation. If a string is passed in, it is treated as a normal character, and only one substitution operation is performed, and if the regular expression is present with the global (g) modifier, all occurrences of the target character are replaced. Only one substitution operation will be performed.
Replacement: The character you want to replace.
The return value is the string after the substitution operation.
Simple usage of string.replace ()
Copy Code code as follows:

var text = "JavaScript is very powerful!" ";
Text.replace (/javascript/i, "JavaScript");
Back: JavaScript is very powerful!

String.Replace () Replaces all occurrences of the target character
Copy Code code as follows:

var text= "JavaScript is very powerful! JAVASCRIPT is one of my favorite languages! ";
Text.replace (/javascript/ig, "JavaScript");
Back: JavaScript is very powerful! JavaScript is one of my favorite languages!

String.Replace () to implement the swap position
Copy Code code as follows:

var name= "Doe, John";
Name.replace (/(\w+) \s*,\s* (\w+)/, "$ $");
Back: John Doe

String.Replace () implementation replaces all double quotes with characters enclosed in brackets
Copy Code code as follows:

The var text = ' JavaScript ' is very powerful! ';
Text.replace ([^ "]*)"/g, "[$]");
Back: [JavaScript] very powerful!

String.Replace () capitalize all characters first letter
Copy Code code as follows:

var text = ' A journey of a thousand miles begins with single step. '
Text.replace (/\b\w+\b/g, function (word) {
Return word.substring (0,1). toUpperCase () +
Word.substring (1);
});
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.