A few days before the project need to use a phone number, E-mail and regular web site on the baidu to find for a long time, stepped on a pile of pit, many simply don’t have to, and then found the three comparatively perfect regular match, just a little idea, it encapsulates a simple function, bosses, MoXiao few words said, see below the actual function of the code.
The first argument is passed in the field to be matched, the second argument is things like class names and methods normally added to the SPAN tag, and the third argument can add a new regular expression, but it must be in array format
export function regular(str, className, newRegular) {
/ / / (1/3 4 5 6 7 | | | | | 8] [\ d] {9} | 0 [\ d] - [\ d] {2, 3} {7, 8} | 400 [-]? [\d]{3}[-]? [\d]{4})/g; Mobile phone no.
/ / / / \ d \ w + \ b @ [a - zA zA - z0-9] + \. [a-z] + / g mail
// /(https? |http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;] + / - A - Za - z0-9 + & @ # / % = ~ _ |] / g url
let regular = [/ (1/3 4 5 6 7 | | | | | 8] [\ d] {9} | 0 [\ d] - [\ d] {2, 3} {7, 8} | 400 [-]? [\d]{3}[-]? [\d]{4})/g./[\d\w]+\b@[a-zA-ZA-z0-9]+\.[a-z]+/g./(https? |http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;] +[-A-Za-z0-9+&@#/%=~_|]/g]
/ / cell phone number
let scorePhone = {}
/ / email
let scoreMailbox = {}
/ / url
let scoreWebsite = {}
// The processed field returned
let newFields = str
if (newRegular) {
regular = [...regular, ...newRegular]
}
regular.forEach((item, index) = > {
let obj = {}
obj.index = []
if(str.search(item) ! = = -1) {
obj.textAll = str.match(item)
if (obj.textAll.length) {
obj.textAll.forEach((x, y) = > {
obj.index = [...obj.index, [str.indexOf(x), str.indexOf(x) + str.match(item)[y].length]]
newFields = newFields.replace(item, `<span ${className? className:' '} >${x}</span>`)
})
}
}
index === 0 ? scorePhone = obj : index === 1 ? scoreMailbox = obj : scoreWebsite = obj
})
return {
scorePhone,
scoreMailbox,
scoreWebsite,
newFields
}
}
Copy the code