Describes how to use the JS Regular Expression replace and the jsreplace

Source: Internet
Author: User

Describes how to use the JS Regular Expression replace and the jsreplace

Before talking about the advanced application of replace, let's sort out several important knowledge points in JS regular expressions to help you review your basic knowledge, then I will explain how to use the JS Regular Expression in replace and several typical cases.

I. Create a regular expression

There are two ways to create JS Regular Expressions: new RegExp () and direct literal.

// Use the RegExp object to create var regObj = new RegExp ("(^ \ s +) | (\ s + $)", "g "); // create var regStr =/(^ \ s +) | (\ s + $)/g;

G indicates full-text matching, and I and m are related to it. I indicates case-insensitive matching, and m indicates multi-row matching. If multiple conditions are used at the same time, they are written as: gmi

Ii. Differences between (), [], and {}

() Is used to extract matched strings. When there are several () in the expression, several matching strings will be obtained. For example, (\ s +) indicates a string with consecutive spaces.

[] Is to define the matching character range. For example, [a-zA-Z0-9] indicates that the character text must match English characters and numbers.

{} Is generally used to indicate the length of a match. For example, \ d {3} indicates matching three spaces, and \ d [1, 3] indicates Matching 1 ~ Three spaces.

3. ^ and $

^ Matches the start of a string. For example, (^ a) matches a string starting with the letter.

$ Matches the end of a string. For example, (B $) matches a string ending with the letter B.

^ Another function is to obtain the inverse. For example, [^ xyz] indicates that the matched string does not contain xyz.

Note that: If ^ appears in [], it generally indicates the inverse, and appears elsewhere, it is the beginning of a matching string.

Iv. \ d \ s \ w.

\ D matches a non-negative integer, which is equivalent to [0-9]

\ S matches a blank character

\ W matches an English letter or number, which is equivalent to [0-9a-zA-Z]

. Match any character except linefeed, equivalent to [^ \ n]

V. * +?

* Indicates matching the previous element 0 or multiple times. For example, (\ s *) indicates matching 0 or multiple spaces.

+ Indicates matching the previous element once or multiple times. For example, (\ d +) indicates matching a string consisting of at least one integer.

? Matches the first element 0 or 1 times, equivalent to {0, 1}, for example (\ w ?) Match a string consisting of up to one letter or number

6. test and match

Most of the above are the syntax of JS regular expressions, while test is used to check whether a string matches a regular expression. If it matches, true is returned. Otherwise, false is returned.

/\d+/.test("123") ; //true/\d+/.test("abc") ; //false

Match is the result of obtaining the regular expression matching, Which is returned as an array.

"186a619b28". match (/\ d +/g); // ["186", "619", "28"]

The above is basically the basic knowledge that I often use. It is not comprehensive. If it is not commonly used, it is not listed, because listing is just a decoration. Instead, it is obfuscated with primary and secondary knowledge!

VII. replace

Replace itself is a JavaScript string object method that can receive two parameters:

Replace ([RegExp | String], [String | Function])
The 1st parameters can be a common string or a regular expression.

The 2nd parameters can be a common string or a callback function.

If the first 1st parameters are RegExp, JS will first extract the results of RegExp matching, and then replace the matching results with the first 2nd parameters.

If the first parameter is a callback function, the callback is performed once every matching result. The following parameters are passed in each callback:

Result: The matched result $1,... $9: The regular expression contains several () parameters, which are passed ~ $9 represents the extracted results of each () in this match, with a maximum of 9 offsets: records the start position of this match. source: receives the matched original string.

The following are several typical cases of using replace and JS Regular Expressions:

(1) Implement the trim function of the string and remove spaces on both sides of the string

String. prototype. trim = function () {// Method 1: replace return this with "" for each matching result. replace (/(^ \ s +) | (\ s + $)/g, function () {return "" ;}); // Method 2: same as method 1, return this. replace (/(^ \ s +) | (\ s + $)/g ,'');};

^ \ S + indicates the consecutive white space characters starting with a space, \ s + $ indicates the consecutive white space characters ending with a space, and () is used to extract the matching results, because it is |, the expression will match up to two result sets, and then perform two replications:

String. prototype. trim = function () {/*** @ param rs: matching result * @ param $1: 1st () extracted results * @ param $2: 2nd () extracted result * @ param offset: Match start position * @ param source: original string */this. replace (/(^ \ s +) | (\ s + $)/g, function (rs, $1, $2, offset, source) {// each element in arguments corresponds to a parameter console. log (arguments) ;}) ;}; "abcd ". trim (); output result: ["", "", undefined, 0, "abcd"] // 1st matching results ["", undefined, "", 5, "abcd"] // 2nd matching results

(2) extract the parameter names and parameter values in the browser url to generate a key/value object.

Function getUrlParamObj () {var obj ={}; // obtain the url parameter part var params = window. location. search. substr (1); // [^ & =] + indicates the consecutive characters not including & OR =, plus () is to extract the corresponding string params. replace (/([^ & =] +) = ([^ & =] *)/gi, function (rs, $1, $2) {obj [$1] = $2;}); return obj ;}

/([^ & =] +) = ([^ & =] *)/Gi matches a complete key/value, for example, xxxx = xxx, every time such a result is matched, a callback is executed and the matched key and value are passed, corresponding to $1 and $2.

(3) Insert a new string at the specified position of the string

String. prototype. insetAt = function (str, offset) {// use RegExp () to create a regular expression var regx = new RegExp ("(. {"+ offset +"}) "); return this. replace (regx, "$1" + str) ;}; "abcd ". insetAt ('xyz', 2); // insert xyz> "abxyzcd" between B and c"

When offset = 2, the regular expression is :( ^. {2 }). represents any character except \ n, followed by {2} is to match the first two consecutive characters consisting of digits or letters, plus () will extract the matching results, replace the matched result with a new string, such as: Result = Result + str

(4) convert the mobile phone number 12988886666 to 129 8888 6666

Function telFormat (tel) {tel = String (tel); // method 1 return tel. replace (/(\ d {3}) (\ d {4}) (\ d {4})/, function (rs, $1, $2, $3) {return $1 + "" + $2 + "" + $3}); // method 2 return tel. replace (/(\ d {3}) (\ d {4}) (\ d {4})/, "$1 $2 $3 ");}

(\ D {3} \ d {4} \ d {4}) can match the complete mobile phone number and extract the first 3, 4-7, and 8-11 digits, respectively, "$1 $2 $3" is a new string consisting of three result sets with spaces, and then the complete mobile phone number is replaced.

(5) Implement the escapeHtml function to escape <,>, &,"

Function escapeHtml (str) {// match <> "& return str. replace (/[<> "&]/g, function (rs) {switch (rs) {case" <": return" <"; case"> ": return ">"; case "&": return "&"; case "\" ": return """;}});}

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • How to Use the replace method and regular expression in Javascript
  • Javascript replace method and Regular Expression
  • Regular expression syntax based on the replace function in javascript
  • Use of the replace function in js Regular Expressions
  • Application Case Study of js replace regular expression
  • JS and replace use regular expressions to replace all SQL parameters with data in the specified format
  • JS uses the replace () method and regular expression to search and replace strings.
  • How to replace a mobile phone number with replace () in a javascript Regular Expression
  • Detailed description of the replace method in the javascript Regular Expression

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.