Use js to replace character replace () in a string

Source: Internet
Author: User

In js, we can use replace () to replace the characters, numbers, or letters in the string, or replace () with regular expressions, below I will introduce some common methods of character replacement.

For example

The Code is as follows:

Var str = "are all men? Isn't it! ";
Str = str. replace ');
Alert (str );


In the above Code, only the first "?" is replaced, and the output is "Everyone is a man, isn't it! ", Hey

If you want to replace all the content in the string that meets the conditions, it is good to replace it with a regular expression. The following code can replace all

The Code is as follows:

Var str = 'are all men? Isn't it? ';
Str = str. replace (/?/g, well ');
Alert (str );


In this way, we will output "Everyone is a man, isn't it? ", All the content that meets the condition is replaced. Note that the regular expression/?/g indicates g, which indicates global, if this configuration item is not set, it will not be completely replaced.

Example

The Code is as follows:

<Script type = "text/javascript">
Var str = "www. bKjia. c0paa"
Document. write (str. replace (/aa/, ") // The output result is www. bKjia. c0m.
</Script>

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 (/bw + B/g, function (word ){
Return word. substring (0, 1). toUpperCase () + word. substring (1 );
});


Related Article

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.