JS string replacement function replace () detailed introduction

Source: Internet
Author: User

Grammar

Stringobject.replace (regexp/substr,replacement)

Replace
Used to find a string that matches a regular expression, and then use a new string instead of a matching string.

The code is as follows Copy Code
var result1 = A.replace (Re, "Hello");
RESULT1 = "Hello"
var result2 = B.replace (Re, "Hello");
RESULT2 = ", World"


Example 1

The code is as follows Copy Code

<script language= "JavaScript" >
var strm = "JavaScript is a good script language";
Here I want to replace the letter A with the letter A
Alert (Strm.replace ("A", "a"));
</script>

The substitution above is simple, and we say that replace can be replaced with a regular match.

Example 2

The code is as follows Copy Code

<script language= "JavaScript" >
var strm = "JavaScript is a good script language";
Replace the letter a all with the letter A
Alert (Strm.replace (/a/g, "a"));
</script>

Replace all characters to replace

Replace the letter I all with 5

  code is as follows copy code

<script language= "javascript"
var txt = "Sjfisjfisdjfijsidfjioalfjewofjjgs";
Alert (txt. replace (/i/g, "5"));
</script>


///replace only the first letter I with 5

<script language= "javascript"
var txt = " Sjfisjfisdjfijsidfjioalfjewofjjgs ";
Alert (txt. replace ("I", "5"));
</script>

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.