1. Why use regular expressions?#
Example#
Suppose there is a string:
const result="124ssabc33501fs"
Now I only want to extract the numbers from it. How can I do that?
Of course, you might think of doing it like this:
let r1=[...result].filter((item,index)=>!Number.isNAN(item)).join("")
Although it is only one line, it is not the most elegant solution.
If we use regular expressions:
console.log(result.match("/\d/g").join())
We can match all the numbers.
Ways to create regular expressions#
Literal creation#
let oo="lhw"
console.log(/w/.test(oo)) //check if there is a 'w' character
But what if 'w' is a variable?
let oo="lhw"
const h="h"
console.log(eval(`/${h}/`.test(oo)))
Object creation#
let oo="luhw"
let a="h"
let a2="\\w" //match underscore
let a3="\\d" //match digit
let reg=new RegExp("u","g") //match substring, globally
let reg2=new RegExp(a,"g") //accepts variables, more convenient than literals
reg.test(oo)
Example#
Example: Replace the corresponding text in a div when the user inputs text.
<div class="content">lhwwoc</div>
<script>
let content=prompt("Please enter content")
let reg=new RegExp(content,"g")
const element=doucument.qureySelector(".content")
// let str=content.replace(/\w/,str=>{})
element.innerHtml.replace(reg,str=>{
return `<span style="color:red">
${str}
</span>`
})
</script>
Alternation#
Similar to logical OR (||)
const str="newnewnwec"
console.log(/@|n/.test()) //true
console.log(/@|o/.test()) //false
console.log(/wne|n/.test()) //true
Foreshadowing#
Suppose I want to check if a phone number is from Beijing or Shanghai.
/(010|020)\-\d{7,8}}/.test("010-12309721")
//true
/(010|020)\-\d{7,8}}/.test("assd010-12309721")
//false
We can see that there is no restriction on the beginning and end.
Next, we will explain the concept of character classes.
let reg=/[123456]/
let age="18"
reg.test("1") //true
age.match(reg) //returns [1] //only matches one character
If we replace [] with ()
//
let reg=/(18|34|56)/
let age="18"
reg.test("1") //false
age.match(reg) //returns ["18","18",index:0]