Home  >  Article  >  Web Front-end  >  Examples of clever use of regular expressions in JavaScript

Examples of clever use of regular expressions in JavaScript

巴扎黑
巴扎黑Original
2017-08-16 10:50:561330browse

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!

Statement:
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