企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] * * * * * ## 1 正则函数 ### 1-1 test() 检测一个字符串是否匹配某个模式 ~~~ RegExpObject.test(string) ~~~ > string:必需,要检测的字符串 > 返回值:如果字符串 string 中含有与 RegExpObject 匹配的文本,则返回 true,否则返回 false 实例 ~~~ <script type="text/javascript"> var str = "Visit W3School"; var patt1 = new RegExp("W3School"); var result = patt1.test(str); document.write("Result: " + result); </script> ~~~ 输出 ~~~ Result: true ~~~ ### 1-2 replace() 替换字符串中的一些字符。 ~~~ stringObject.replace(regexp/substr,replacement) ~~~ > regexp/substr: > 子字符串或要替换模式的RegExp对象。默认替换第一个匹配子串,使用全局标识g,则替换所有匹配子串 > replacement: > 规定了替换文本或生成文本的函数 > 返回值,返回替换后字符串。 > 字符串每个匹配都将由字符串替换,$为索引,函数则第一个参数是匹配模式的字符串,接下来的参数是与模式中的子表达式匹配的字符串,可以有0个或多个这样的参数。接下来的参数是一个整数,声明了匹配的位置,最后一个参数是stringObject本身 实例1 ~~~ <script type="text/javascript"> var str="Visit Microsoft!" document.write(str.replace(/Microsoft/, "W3School")) </script> ~~~ 输出 ~~~ Visit W3School! ~~~ 实例2 ~~~ <script type="text/javascript"> var str="Welcome to Microsoft! " str=str + "We are proud to announce that Microsoft has " str=str + "one of the largest Web Developers sites in the world." document.write(str.replace(/Microsoft/g, "W3School")) </script> ~~~ 输出 ~~~ Welcome to W3School! We are proud to announce that W3School has one of the largest Web Developers sites in the world. ~~~ 实例3 ~~~ name = "Doe, John"; name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"); ~~~ 实例4 ~~~ name = '"a", "b"'; name.replace(/"([^"]*)"/g, "'$1'"); ~~~ 实例5 ~~~ name = '"a", "b"'; name.replace(/"([^"]*)"/g, "'$1'"); ~~~ 实例6 ~~~ name = 'aaa bbb ccc'; uw=name.replace(/\b\w+\b/g, function(word){ return word.substring(0,1).toUpperCase()+word.substring(1);} ); ~~~ ### 1-3match() 在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。 ~~~ stringObject.match(searchvalue) stringObject.match(regexp) ~~~ > searchvalue:规定检索的字符串值 > regexp: 规定匹配的模式的RegExp对象 > 返回值:存放匹配结果的数组,默认为第一个,全局/g则返回匹配结果 查找失败返回null,查找成功返回包含一个的数组。第0个元素存放的是匹配文本,其余元素存放的是与正则表达式的子表达式匹配的文本。 > 无/g,返回数组还包含两个对象属性,index属性起始字符的位置,input属性对stringObject的引用 > 包含/g,执行全局搜索,搜索所有匹配子字符串,查找失败返回null,匹配一个或多个,返回一个数组。全局返回不包含index属性或input属性 实例1 ~~~ <script type="text/javascript"> var str="Hello world!" document.write(str.match("world") + "<br />") document.write(str.match("World") + "<br />") document.write(str.match("worlld") + "<br />") document.write(str.match("world!")) </script> ~~~ 输出 ~~~ world null null world! ~~~ 实例2 ~~~ <script type="text/javascript"> var str="1 plus 2 equal 3" document.write(str.match(/\d+/g)) </script> ~~~ 输出 ~~~ 1,2,3 ~~~