


Detailed explanation of how to use JS regular replace_javascript skills
在讲replace的高级应用之前,我们先简单梳理一下JS正则中的几个重要的知识点,以帮助你对基础知识的回顾,然后再讲解JS正则表达式在replace中的使用,以及常见的几个经典案例。
一、正则表达式的创建
JS正则的创建有两种方式: new RegExp() 和 直接字面量。
//使用RegExp对象创建 var regObj = new RegExp("(^\s+)|(\s+$)","g"); //使用直接字面量创建 var regStr = /(^\s+)|(\s+$)/g;
其中 g 表示全文匹配,与之相关的还有 i 和m,i 表示匹配时忽略大小写,m 表示多行匹配,如果多个条件同时使用时,则写成:gmi
二、()、[]、{} 的区别
() 的作用是提取匹配的字符串。表达式中有几个()就会得到几个相应的匹配字符串。比如 (\s+) 表示连续空格的字符串。
[]是定义匹配的字符范围。比如 [a-zA-Z0-9] 表示字符文本要匹配英文字符和数字。
{}一般用来表示匹配的长度,比如 \d{3} 表示匹配三个空格,d[1,3]表示匹配1~3个空格。
三、^ 和 $
^ 匹配一个字符串的开头,比如 (^a) 就是匹配以字母a开头的字符串
$ 匹配一个字符串的结尾,比如 (b$) 就是匹配以字母b结尾的字符串
^ 还有另个一个作用就是取反,比如[^xyz] 表示匹配的字符串不包含xyz
需要注意的是:如果^出现在[]中一般表示取反,而出现在其他地方则是匹配字符串的开头
四、d \s \w .
\d 匹配一个非负整数, 等价于 [0-9]
\s 匹配一个空白字符
\w 匹配一个英文字母或数字,等价于[0-9a-zA-Z]
. 匹配除换行符以外的任意字符,等价于[^\n]
五、* + ?
* 表示匹配前面元素0次或多次,比如 (\s*) 就是匹配0个或多个空格
+ 表示匹配前面元素1次或多次,比如 (\d+) 就是匹配由至少1个整数组成的字符串
? 表示匹配前面元素0次或1次,相当于{0,1} ,比如(\w?) 就是匹配最多由1个字母或数字组成的字符串
六、test 、match
前面的大都是JS正则表达式的语法,而test则是用来检测字符串是否匹配某一个正则表达式,如果匹配就会返回true,反之则返回false
/\d+/.test("123") ; //true /\d+/.test("abc") ; //false
match是获取正则匹配到的结果,以数组的形式返回
"186a619b28".match(/\d+/g); // ["186","619","28"]
以上基本上是我经常用到的基础知识,不是很全面,不常用的就没有列出来,因为列出来也只是摆设,反而混淆主次!
七、replace
replace 本身是JavaScript字符串对象的一个方法,它允许接收两个参数:
replace([RegExp|String],[String|Function])
第1个参数可以是一个普通的字符串或是一个正则表达式
第2个参数可以是一个普通的字符串或是一个回调函数
如果第1个参数是RegExp, JS会先提取RegExp匹配出的结果,然后用第2个参数逐一替换匹配出的结果
如果第2个参数是回调函数,每匹配到一个结果就回调一次,每次回调都会传递以下参数:
result: 本次匹配到的结果 $1,...$9: 正则表达式中有几个(),就会传递几个参数,$1~$9分别代表本次匹配中每个()提取的结果,最多9个 offset:记录本次匹配的开始位置 source:接受匹配的原始字符串
以下是replace和JS正则搭配使用的几个常见经典案例:
(1)实现字符串的trim函数,去除字符串两边的空格
String.prototype.trim = function(){ //方式一:将匹配到的每一个结果都用""替换 return this.replace(/(^\s+)|(\s+$)/g,function(){ return ""; }); //方式二:和方式一的原理相同 return this.replace(/(^\s+)|(\s+$)/g,''); };
^\s+ 表示以空格开头的连续空白字符,s+$ 表示以空格结尾的连续空白字符,加上() 就是将匹配到的结果提取出来,由于是 | 的关系,因此这个表达式最多会match到两个结果集,然后执行两次替换:
String.prototype.trim = function(){ /** * @param rs:匹配结果 * @param $1:第1个()提取结果 * @param $2:第2个()提取结果 * @param offset:匹配开始位置 * @param source:原始字符串 */ this.replace(/(^\s+)|(\s+$)/g,function(rs,$1,$2,offset,source){ //arguments中的每个元素对应一个参数 console.log(arguments); }); }; " abcd ".trim(); 输出结果: [" ", " ", undefined, 0, " abcd "] //第1次匹配结果 [" ", undefined, " ", 5, " abcd "] //第2次匹配结果
(2)提取浏览器url中的参数名和参数值,生成一个key/value的对象
function getUrlParamObj(){ var obj = {}; //获取url的参数部分 var params = window.location.search.substr(1); //[^&=]+ 表示不含&或=的连续字符,加上()就是提取对应字符串 params.replace(/([^&=]+)=([^&=]*)/gi,function(rs,$1,$2){ obj[$1] = $2; }); return obj; }
/([^&=]+)=([^&=]*)/gi 每次匹配到的都是一个完整key/value,形如 xxxx=xxx, 每当匹配到一个这样的结果时就执行回调,并传递匹配到的key和value,对应到$1和$2
(3)在字符串指定位置插入新字符串
String.prototype.insetAt = function(str,offset){ //使用RegExp()构造函数创建正则表达式 var regx = new RegExp("(.{"+offset+"})"); return this.replace(regx,"$1"+str); }; "abcd".insetAt('xyz',2); //在b和c之间插入xyz >> "abxyzcd"
当offset=2时,正则表达式为:(^.{2}) .表示除 之外的任意字符,后面加{2} 就是匹配以数字或字母组成的前两个连续字符,加()就会将匹配到的结果提取出来,然后通过replace将匹配到的结果替换为新的字符串,形如:结果=结果+str
(4) 将手机号12988886666转化成129 8888 6666
function telFormat(tel){ tel = String(tel); //方式一 return tel.replace(/(\d{3})(\d{4})(\d{4})/,function (rs,$1,$2,$3){ return $1+" "+$2+" "+$3 }); //方式二 return tel.replace(/(\d{3})(\d{4})(\d{4})/,"$1 $2 $3"); }
(\d{3}\d{4}\d{4}) 可以匹配完整的手机号,并分别提取前3位、4-7位和8-11位,"$1 $2 $3" 是在三个结果集中间加空格组成新的字符串,然后替换完整的手机号。
(5) 实现函数escapeHtml,将<, >, &, " 进行转义
function escapeHtml(str) { //匹配< > " & return str.replace(/[<>"&]/g, function(rs) { switch (rs) { case "<": return "<"; case ">": return ">"; case "&": return "&"; case "\"": return """; } }); }
以上就是本文的全部内容,希望对大家的学习有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
