Examples of clever use of regular expressions in JavaScript
Some children must have doubts and spend a lot of time learning regular expressions, but find that they are useless. Regular expressions are just for verifying an email address and are basically useless for other places. In fact, most people feel this way, so Some people simply don't learn it, finding it difficult and of little use. As everyone knows, if you want to become a programming expert, you must play with regular expressions. The excellent open source libraries and frameworks on GitHub are full of powerful regular expressions. The author of jQuery was also called the little prince of regular expressions back then. Here I share some wonderful uses of regular expressions that I use in my work and that I have collected. Sparks of developer wisdom shine everywhere.
There are many ways to achieve a requirement. Which one is better? The wise have different opinions. Here we only provide a comparative thinking to stimulate everyone's interest in learning regularity and develop the thinking of using regularity.
As a front-end developer, you always have your own unique skills. After all, front-end development is different from the back-end. All codes are exposed to users. If the code is redundant, it will affect the bandwidth and reduce the efficiency. Regular Expression (Regular Expression), this is a hard nut to chew, but it is delicious to chew on. So today I will also show you some tricks of regular expressions.
Zhengdafa is good, Zhengdafa is good, Zhengdafa is good, important things should be said three times.
1. Get the value of the link https://www.baidu.com?name=jawil&age=23 name
Non-regular implementation:
function getParamName(attr) { let search = window.location.search // "?name=jawil&age=23" let param_str = search.split('?')[1] // "name=jawil&age=23" let param_arr = param_str.split('&') // ["name=jawil", "age=23"] let filter_arr = param_arr.filter(ele => { // ["name=jawil"] return ele.split('=')[0] === attr }) return decodeURIComponent(filter_arr[0].split('=')[1])} console.log(getParamName('name')) // "jawil"
Use regular expressions to implement:
function getParamName(attr) { let match = RegExp(`[?&]${attr}=([^&]*)`) //分组运算符是为了把结果存到exec函数返回的结果里 .exec(window.location.search) //["?name=jawil", "jawil", index: 0, input: "?name=jawil&age=23"] return match && decodeURIComponent(match[1].replace(/\+/g, ' ')) // url中+号表示空格,要替换掉} console.log(getParamName('name')) // "jawil"
If you don’t understand it, please study this article first: [JS Advanced] test, exec, match, replace
2. Number formatting problem, 1234567890 --> 1,234,567,890
Non-regular implementation:
let test = '1234567890' function formatCash(str) { let arr = [] for (let i = 1; i < str.length; i--) { if (str.length % 3 && i == 1) arr.push(str.substr(0, str.length % 3)) if (i % 3 === 0) arr.push(str.substr(i - 2, 3)) } return arr.join(',') } console.log(formatCash(test)) // 1,234,567,890
Regular implementation:
let test1 = '1234567890'let format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',') console.log(format) // 1,234,567,890
The following is a brief analysis of regular /\B(?=(\d{3})+(?!\d))/g:
/\B (?=(\d{3})+(?!\d))/g: Regular matching boundary \B, the boundary must be followed by (\d{3})+(?!\d);
( \d{3})+: must be 1 or more 3 consecutive numbers;
(?!\d): The 3 numbers in step 2 are not allowed to be followed by numbers;
(\ d{3})+(?!\d): So the matching boundary must be followed by 3*n (n>=1) numbers.
Finally replace all matched boundaries to achieve the goal.
3. Remove the spaces on the left and right sides of the string, " jaw il " --> "jaw il"
Non-regular implementation:
function trim(str) { let start, end for (let i = 0; i < str.length; i++) { if (str[i] !== ' ') { start = i break } } for (let i = str.length - 1; i > 0; i--) { if (str[i] !== ' ') { end = i break } } return str.substring(start, end - 1) } let str = " jaw il "console.log(trim(str)) // "jaw il"
Use regular expressions to implement:
function trim(str) { return str.replace(/(^\s*)|(\s*$)/g, "") } let str = " jaw il "console.log(trim(str)) // "jaw il"
4. Determine whether a number is a prime number 3 --> true
Prime numbers are also known as Prime number. Refers to a natural number greater than 1 that is not divisible by other natural numbers except 1 and the integer itself.
Non-regular implementation:
function isPrime(num){ // 不是数字或者数字小于2 if(typeof num !== "number" || !Number.isInteger(num)){ // Number.isInterget 判断是否为整数 return false } //2是质数 if(num == 2){ return true }else if(num % 2 == 0){ //排除偶数 return false } //依次判断是否能被奇数整除,最大循环为数值的开方 let squareRoot = Math.sqrt(num) //因为2已经验证过,所以从3开始;且已经排除偶数,所以每次加2 for(let i = 3; i <= squareRoot; i += 2) { if (num % i === 0) { return false } } return true} console.log(isPrime(19)) // true
Regular implementation:
function isPrime(num) {return !/^1?$|^(11+?)\1+$/.test(Array(num+1).join('1'))} console.log(isPrime(19)) // true
要使用这个正规则表达式,你需要把自然数转成多个1的字符串,如:2 要写成 “11”, 3 要写成 “111”, 17 要写成“11111111111111111”,这种工作使用一些脚本语言可以轻松的完成,JS实现也很简单,我用Array(num+1).join('1')这种方式实现了一下。
一开始我对这个表达式持怀疑态度,但仔细研究了一下这个表达式,发现是非常合理的,下面,让我带你来细细剖析一下是这个表达式的工作原理。
首先,我们看到这个表达式中有“|”,也就是说这个表达式可以分成两个部分:/^1?$/ 和 /^(11+?)\1+$/
第一部分:/^1?$/, 这个部分相信不用我多说了,其表示匹配“空串”以及字串中只有一个“1”的字符串。
第二部分:/^(11+?)\1+$/ ,这个部分是整个表达式的关键部分。其可以分成两个部分,(11+?) 和 \1+$ ,前半部很简单了,匹配以“11”开头的并重复0或n个1的字符串,后面的部分意思是把前半部分作为一个字串去匹配还剩下的字符串1次或多次(这句话的意思是——剩余的字串的1的个数要是前面字串1个数的整数倍)。
可见这个正规则表达式是取非素数,要得到素数还得要对整个表达式求反。通过上面的分析,我们知道,第二部分是最重要的,对于第二部分,举几个例子,
示例一:判断自然数8。我们可以知道,8转成我们的格式就是“11111111”,对于 (11+?) ,其匹配了“11”,于是还剩下“111111”,而 \1+$ 正好匹配了剩下的“111111”,因为,“11”这个模式在“111111”出现了三次,符合模式匹配,返回true。所以,匹配成功,于是这个数不是质数。
示例二:判断自然数11。转成我们需要的格式是“11111111111”(11个1),对于 (11+?) ,其匹配了“11”(前两个1),还剩下“111111111”(九个1),而 \1+$ 无法为“11”匹配那“九个1”,因为“11”这个模式并没有在“九个1”这个串中正好出现N次。于是,我们的正则表达式引擎会尝试下一种方法,先匹配“111”(前三个1),然后把“111”作为模式去匹配剩下的“11111111”(八个1),很明显,那“八个1”并没有匹配“三个1”多次。所以,引擎会继续向下尝试……直至尝试所有可能都无法匹配成功。所以11是素数。
通过示例二,我们可以得到这样的等价数算算法,正则表达式会匹配这若干个1中有没有出现“二个1”的整数倍,“三个1”的整数倍,“四个1”的整数倍……,而,这正好是我们需要的算素数的算法。现在大家明白了吧。
5、字符串数组去重 ["a","b","c","a","b","c"] --> ["a","b","c"]
这里只考虑最简单字符串的数组去重,暂不考虑,对象,函数,NaN等情况,这种用正则实现起来就吃力不讨好了。
非正则实现:
①ES6实现
let str_arr=["a","b","c","a","b","c"] function unique(arr){ return [...new Set(arr)]} console.log(unique(str_arr)) // ["a","b","c"]
②ES5实现
var str_arr = ["a", "b", "c", "a", "b", "c"] function unique(arr) { return arr.filter(function(ele, index, array) { return array.indexOf(ele) === index })} console.log(unique(str_arr)) // ["a","b","c"]
③ES3实现
var str_arr = ["a", "b", "c", "a", "b", "c"] function unique(arr) { var obj = {}, array = [] for (var i = 0, len = arr.length; i < len; i++) { var key = arr[i] + typeof arr[i] if (!obj[key]) { obj[key] = true array.push(arr[i]) } } return array } console.log(unique(str_arr)) // ["a","b","c"]
额,ES4呢。。。对不起,由于历史原因,ES4改动太大,所以被废弃了。
可以看到从ES3到ES6,代码越来越简洁,JavaScript也越来越强大。
The above is the detailed content of Examples of clever use of regular expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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 WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

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

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

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

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

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
