Match and replace methods for strings in JavaScript

Source: Internet
Author: User

1. Match method

The match () method retrieves the specified value within a string, or finds a match for one or more regular expressions.

The return value of the match () method is: An array that holds the matching results .

2. Replace method

The replace () method is used to replace other characters with some characters in a string, or to replace a substring that matches a regular expression.

The return value of the Replace method is: a new string .

3. Description

The parameters of the above 2 methods are mainly to add global g when using regular expressions, so that the string can be fully matched or replaced.

Example code:

<!DOCTYPE HTML><HTMLLang= "zh">    <Head>        <MetaCharSet= "UTF-8" />        <title>Match and replace methods for strings in JavaScript</title>    </Head>    <Body>        <!--Note that the SRC path should be -        <Scriptsrc= "Js/jquery-1.12.4.min.js"type= "Text/javascript"CharSet= "Utf-8"></Script>        <Scripttype= "Text/javascript">            varStr= "1 plus 2 equal 3"; //The match method returns an array of values            vararr=Str.match (/[0-9]/g) Console.log (arr); varNew_str=Str.replace (/[0-9]/G,'Newstr'); //Replace method returns a value of new stringConsole.log (NEW_STR)</Script>    </Body></HTML>

The console output is:

Match and replace methods for strings in JavaScript

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.