实现一个需求的方法很多种,哪种更好,仁者见仁智者见智,这里只提供一种对比的思维来激发大家学习正则的兴趣和养成活用正则的思维。
作为前端开发人员,总会有点自己的奇技淫巧,毕竟前端开发不同于后端,代码全部暴漏给用户不说,代码冗余了少则影响带宽,多则效率降低。正则表达式(Regular Expression),这是一块硬骨头,很难啃,但是啃着又很香。所以今天我也来爆一些正则表达式的奇技淫巧。
正则大法好,正则大法好,正则大法好,重要的事情说三遍。
1、获取链接 https://www.baidu.com?name=jawil&age=23 name的value值
非正则实现:
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"
用正则实现:
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"
2、 数字格式化问题,1234567890 --> 1,234,567,890
非正则实现:
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
用正则实现:
let test1 = '1234567890' let format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',') console.log(format) // 1,234,567,890
下面简单分析下正则/\B(?=(\d{3})+(?!\d))/g:
/\B(?=(\d{3})+(?!\d))/g:正则匹配边界\B,边界后面必须跟着(\d{3})+(?!\d);
(\d{3})+:必须是1个或多个的3个连续数字;
(?!\d):第2步中的3个数字不允许后面跟着数字;
(\d{3})+(?!\d):所以匹配的边界后面必须跟着3*n(n>=1)的数字。
最终把匹配到的所有边界换成,即可达成目标。
3、去掉字符串左右两边的空格," jaw il " --> “jaw il”
非正则实现:
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"
用正则实现:
function trim(str) { return str.replace(/(^\s*)|(\s*$)/g, "") } let str = " jaw il " console.log(trim(str)) // "jaw il"
4、判断一个数是否是质数 3 --> true
质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数。
非正则实现:
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
用正则实现:
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也越来越强大。
用正则实现:
var str_arr = ["a", "b", "c", "a", "b", "c"] function unique(arr) { return arr.sort().join(",,"). replace(/(,|^)([^,]+)(,,\2)+(,|$)/g, "$1$2$4"). replace(/,,+/g, ","). replace(/,$/, ""). split(",") } console.log(unique(str_arr)) // ["a","b","c"]
The above is the detailed content of How to use JavaScript regular expressions flexibly. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor
