Escaping#
Assuming you want to validate a number with a decimal point, the syntax is as follows:
let str = 12.24
// . represents any character except a line break, so it needs to be escaped
// /.
/\d+\.\d+/.test(str) //true
// /\d+ matches one or more digits
Creating with an object
// Note that a string is passed here, not a literal.
let reg = new RegExp("\d+\.\d+","g")
reg.test(str) //false
Why can the literal match but the object cannot match for the same pattern?
Reason
console.log("/d"==="d") //true
console.log("//d"==="/d") //true
Therefore, when creating an object:
// Note that a string is passed here, not a literal.
let reg = new RegExp("\\d+\\.\\d+","g")
reg.test(str) //false
Example#
Defining a URL:
let url = "https://www.example.com"
log(/https?:\/\/\w+\.\w+\.\w+/.test(url))
Example 2#
Assuming you want the username to start with a letter and not exceed 15 characters with a number at the end.
<input name="user" type="text">
<srcipt>
const ele = document.querySelector("[name='user']")
ele.addEventLisitenr("keyup",function(){
this.value.match(/^[a-z]/w{3,14}$/)
})
</srcipt>