前端正则表达式

    xiaoxiao2022-06-30  54

    ECMAScript v3 规定,replace() 方法的参数 replacement 可以是函数而不是字符串。在这种情况下,每个匹配都调用该函数,它返回的字符串将作为替换文本使用。该函数的第一个参数是匹配模式的字符串。接下来的参数是与模式中的子表达式匹配的字符串,可以有 0 个或多个这样的参数。接下来的参数是一个整数,声明了匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。

    将特殊字符&<">'·,转义;如果是转义后的字符(能够匹配子串),不再转义

    name = '&aaa bbb>· ccc· &'; //特殊字符转义,已经转义的不再二次转义 console.log(name); var reg = /[&<">'·](?:(amp|lt|quot|gt|#39|middot|nbsp|#\d+);)?/g uw = name.replace(reg, function(a, b) { console.log(a + ' ' + b) if(b) { console.log(b + '=true then return ' + a) //console.log('</br>') return a; } else { return { '<': '<', '&': '&', '"': '"', '>': '>', '·': ''', "'": '·' }[a] } }) console.log(uw);

    完整表达式  & /[&<">'·](?:(amp|lt|quot|gt|#39|middot|nbsp|#\d+);)?/g 子表达式   amp 子表达式语法:  :(***)    (amp|lt|quot|gt|#39|middot|nbsp|#\d+) 返回值为  return   json[key]

    转载请注明原文地址: https://ju.6miu.com/read-1125700.html

    最新回复(0)