The use method of JS regular replace _javascript skill

Source: Internet
Author: User

Before we talk about the advanced application of replace, we first comb a few important knowledge points in JS, to help you review the basics, then explain the use of JS regular expressions in replace, and a few classic cases.

First, the creation of regular expressions

JS Regular is created in two ways: New RegExp () and direct literal.

Use the RegExp object to create
the var regobj = new RegExp ("(^\s+) |" ( \s+$) "," G ");

Use direct literal to create
var regstr =/(^\s+) | ( \s+$)/g;

Where g indicates full-text matching, and related to the I and m,i indicate that the match ignores case, M is a multiline match, if multiple conditions are used simultaneously, then write: GMI

The difference between (), [], {}

The role of () is to extract a matching string. A few () of the expressions will get a couple of corresponding matching strings. For example (\s+) A string that represents a contiguous space.

[] is the range of characters that define the match. For example, [a-za-z0-9] means that character text matches English characters and numbers.

{} is typically used to indicate the length of a match, such as \d{3} to match three spaces, \d[1,3] to match 1~3 spaces.

Three, ^ and $

^ matches the beginning of a string, such as (^a) a string that matches the beginning of the letter A

$ matches the end of a string, such as (b$) a string that matches the end of the letter B

^ Another function is to reverse, for example, [^XYZ] indicates that a matching string does not contain XYZ

It should be noted that if ^ appears in [] generally represents the reverse, and the other place is the beginning of the matching string

Four, \d \s \w.

\d matches a nonnegative integer, equivalent to [0-9]

\s match a white space character

\w match an English letter or number, equivalent to [0-9a-za-z]

. Matches any character except the newline character, equivalent to [^\n]

Five, * +?

* means to match the preceding element 0 or more times, for example (\s*) is to match 0 or more spaces

+ indicates that matching the preceding element 1 or more times, for example (\d+), matches a string of at least 1 integers

? Represents a match to the preceding element 0 or 1 times, equivalent to {0,1}, such as (\w?) A string that matches up to 1 letters or numbers

Test, Match

Most of the front is a JS regular expression syntax, and test is used to detect whether a string matches a regular expression, if the match will return true, Vice return false

/\d+/.test ("123"); True

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

Match is to get the result of a regular match and return as an array

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

The above is basically I often use the basic knowledge, is not very comprehensive, not commonly used is not listed, because the list is only equipment, but confused primary and secondary!

VII. Replace

The replace itself is a method of a JavaScript string object that allows two parameters to be received:

Replace ([regexp| String],[string| Function])
The 1th argument can be a normal string or a regular expression

The 2nd argument can be a normal string or a callback function.

If the 1th parameter is regexp, JS extracts the result of the RegExp match, and then replaces the matching result with the 2nd parameter.

If the 2nd argument is a callback function, the callback is invoked once for each match to one result, and each callback passes the following arguments:

Result: The results of this match are

,... $: There are several () in the regular expression that pass several arguments, $1~$9 each () of the results of each () fetch in this match, with a maximum of 9

offset: Record the start

of this match Source: Accept Matching raw string

Here are a few common classic examples of replace and JS matching use:

(1) Implement the Trim function of the string, and remove the spaces on either side of the string

String.prototype.trim = function () {

  //mode one: Replace each result that matches to return
  this.replace (^\s+) | ( \s+$)/g,function () {return
    "";
  });

  Mode two: The same principle as mode one return
  this.replace (/(^\s+) | ( \s+$)/g, ');


^\s+ represents a contiguous whitespace character that begins with a space, \s+$ represents a contiguous white space ending with a space, plus () is the result of the match being extracted, because it is | So that the expression will match up to two result sets, and then perform a two-time substitution:

String.prototype.trim = function () {
  /**
   * @param rs: match result
   * @param $1th () Extract result
   * @param $: 2nd () Extract result
   * @param offset: matching start position
   * @param Source: Original string
  /This.replace (/(^\s+) | ( \s+$)/g,function (rs,$1,$2,offset,source) {
    //arguments each element corresponds to an argument
    console.log (arguments);
  });

"ABCD". Trim ();

Output:

["," ", Undefined, 0," ABCD "]//1th time match result
[" ", Undefined," ", 5," ABCD "]//2nd time match result


(2) extracting parameter names and parameter values from the URL of the browser to generate a Key/value object

function Geturlparamobj () {
  var obj = {};
  Gets the parameter part of the URL
  var params = window.location.search.substr (1);
  [^&=]+ represents a continuous character without & or =, plus () is the extraction of the corresponding string
  params.replace ([^&=]+) = ([^&=]*)/gi,function (rs,$1,$2 {
    obj[$1] = $;
  });

  return obj;
}

/([^&=]+) = ([^&=]*)/gi each match to a complete key/value, shaped like Xxxx=xxx, performs a callback whenever a result is matched to one, and passes the matching key and value, corresponding to the $ and $

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

String.prototype.insetAt = function (str,offset) {

  ///Use REGEXP () constructor to create regular expression
  var regx = new RegExp ("(. {") +offset+ "})");

  Return This.replace (REGX, "$" +str);
};

" ABCD ". Insetat (' xyz ', 2); Insert xyz
>> "ABXYZCD" between B and C

When offset=2, the regular expression is: (^.{ 2}). Represents any character other than \ n, the following {2} matches the first two consecutive characters of a number or letter, plus () extracts the matching results and replaces the matching results with the new string with replace, as follows: result = result +str

(4) Convert mobile number 12988886666 to 129 8888 6666

function Telformat (tel) {

  Tel = String (tel);

  Mode one return
  tel.replace (/(\d{3}) (\d{4}) (\d{4})/,function (rs,$1,$2,$3) {return
    $1+ "" +$2+ "" +$3
  });

  Mode two return
  tel.replace (/(\d{3}) (\d{4}) (\d{4})/, "$ $");
}

(\d{3}\d{4}\d{4}) can match the full cell phone number, and extract the first 3 digits, 4-7 bits and 8-11 bits respectively, "$ $" is a new string with a space in the middle of three result sets, then replace the full cell phone number.

(5) Implement function escapehtml, which will be escaped by

function escapehtml (str) {
  //Match < > "& return
  str.replace (/[<>" &]/g, function (RS) {
    Switch (RS) {case
      ' < ': return
        ' < ';
      Case ">": Return
        ">";
      Case "&": Return
        "&";
      Case "\" ": Return
        " "";}}
  );

The above is the entire content of this article, I hope to help you learn.

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.