Home Web Front-end JS Tutorial Detailed explanation of the regular expression replace example of the string object method in js

Detailed explanation of the regular expression replace example of the string object method in js

Apr 18, 2017 am 11:11 AM
js replace string

本篇文章主要介绍了js中string之正则表达式replace方法详解,replace方法是javascript涉及到正则表达式中较为复杂的一个方法,严格上说应该是string对象的方法。

replace方法是javascript涉及到正则表达式中较为复杂的一个方法,严格上说应该是string对象的方法。只不过牵扯到正则的时候比较多一些。需要我们灵活的使用。

语法: stringObj.replace(regexp/substr,replacement);

第一个参数:必需。字符串中要替换的子串或正则RexExp;

第二个参数:必需,一个字符串值,规定了替换文本或生成替换文本的函数。

返回值:注意它的返回值是一个新的字符串,并没有更改原有字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。

所以根据它的参数的不同分为很多种情况,以下一一对各种情况加以分析:

NO.1 两个参数都是字符串


var str1 = '这是一段原始文本,需要替换的内容"这要替换"!';
var newStr = str1.replace('这要替换','need replace');
console.log( newStr );  //输出:  这是一段原始文本,需要替换的内容"need replace"!
Copy after login

上面的例子中第二个参数字符串'need replace',替换掉了第一个参数字符串'这要替换'。这是最简单的一种形式。

NO.2 第一个参数是正则,第二个参数是字符串


var str2 = '这是一段原始文本,需要替换的内容"ac这要替换bb"!';
var newStr = str2.replace( /([a-z])+/g,'qqq' );
console.log( newStr );  //输出:  这是一段原始文本,需要替换的内容"qqq这要替换qqq"!
Copy after login

上面的例子字符串'qqq',替换了正则匹配的内容。如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。

NO.3 第一个参数是正则,第二个参数是带$符的字符串


var str3 = '这是一段原始文本,"3c这要替换4d"!';
var newStr = str3.replace( /([0-9])([a-z])/g,"$1" );
console.log( newStr );  //输出:  这是一段原始文本,"3这要替换4"!';
Copy after login

上面的例子,$1表示regexp中的第一个子表示即([0-9])匹配单个数字,同理若是$2则表示第二个子表示即([a-z]);所以,'3c'这个匹配到的整体被第一个子表示说表示的'3'替换,'4d'被第一个子表示匹配的数字'4'所替换。其他几个同理可得:

(/([0-9])([a-z])/g,”$2″)—>////输出: 这是一段原始文本,”c这要替换d”!'; (3c和4d被相应的第二个子表示匹配出来的c和d替换)(/([0-9])([a-z])/g,”$'”)—>////输出: 这是一段原始文本,”这要替换d”!这要替换”!”!'; (3c被3c右侧文本替换,4d右侧是”!替换,所以出现俩次)

NO.4 第一个参数是正则,第二个参数函数


var str4 = '这是一段原始文本,需要替换的内容"aa这要bbb替换ccccc"!';
var newStr = str4.replace( /[a-z]+/g,function ($0){
  var str = '';
  for (var i = 0; i < $0.length; i++) {
    str += &#39;*&#39;;
  };
  return str;
} );
console.log( newStr );  //这是一段原始文本,需要替换的内容"**这要***替换*****"!
Copy after login

上面的例子函数的第一个参数为匹配的regexp的整体,根据长度函数返回值为相应替换的文本;

NO.5 第一个参数是正则且有子表达式,第二个参数函数且带有多个参数


var str5 = &#39;这是一段原始文本,需要替换的内容"3c这要替换4d"!&#39;;
var newStr = str5.replace( /([0-9])([a-z])/g,function (arg1,arg2,arg3,arg4,arg5){
 console.log( arg1 );
 console.log( arg2 );
 console.log( arg3 );
 console.log( arg4 );
 console.log( arg5 );
} );
Copy after login

输出:

3c
3
c
17
这是一段原始文本,需要替换的内容"3c这要替换4d"!
4d
4
d
23

这是一段原始文本,需要替换的内容"3c这要替换4d"!

上面的例子第一个参数arg1表示匹配的整体,arg2表示第一个子表达式,arg3表示第二个子表达式,接下来的参数arg4是一个整数,声明了表示子匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。

以上就是replace方法各种可能的情况。确实是一个需要深入理解的方法,不过确实也很强大的一个方法,值得深入研究!

The above is the detailed content of Detailed explanation of the regular expression replace example of the string object method in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

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

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

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 JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

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:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles