您好,欢迎访问一九零五行业门户网

javascript中使用正则的方法有哪些

javascript中的正则方法:1、exec(),用于检索字符串中的正则表达式的匹配;2、test(),用于检测一个字符串是否匹配指定正则表达式;3、tostring();4、replace();5、match();6、search()。
本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
什么是正则
正则表达式是描述字符模式的对象。
正则表达式用于对字符串模式匹配及检索替换,是对字符串执行模式匹配的强大工具。
regexp 对象方法
方法描述
compile 在 1.5 版本中已废弃。 编译正则表达式。
exec 检索字符串中指定的值。返回找到的值,并确定其位置。
test 检索字符串中指定的值。返回 true 或 false。
tostring 返回正则表达式的字符串。
支持正则表达式的 string 对象的方法
方法描述ffie
search 检索与正则表达式相匹配的值。 1 4
match 找到一个或多个正则表达式的匹配。 1 4
replace 替换与正则表达式匹配的子串。 1 4
split 把字符串分割为字符串数组。 1 4
javascript exec() 方法
exec() 方法用于检索字符串中的正则表达式的匹配。
如果字符串中有匹配的值返回该匹配值,否则返回 null。
var str="hello world!";//查找"hello"var patt=/hello/g;var result=patt.exec(str);document.write("返回值: " + result); //查找 "php"patt=/php/g;result=patt.exec(str);document.write("<br>返回值: " + result);
javascript test() 方法
test() 方法用于检测一个字符串是否匹配某个模式。
如果字符串中有匹配的值返回 true ,否则返回 false。
var str="hello world!";//查找"hello"var patt=/hello/g;var result=patt.test(str);document.write("返回值: " + result); //查找 "php"patt=/php/g;result=patt.test(str);document.write("<br>返回值: " + result);
javascript regexp tostring() 方法
tostring() 方法返回正则表达式的字符串值。
<!doctype html><html><head><meta charset="utf-8"></head><body><p>点击按钮返回正则表达式的字符串值。</p><button onclick="myfunction()">点我</button> <p id="demo"></p> <script>function myfunction() { var patt = new regexp("", "g"); var res = patt.tostring(); document.getelementbyid("demo").innerhtml = res;}</script></body></html>
javascript replace() 方法
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
<!doctype html><html><head><meta charset="utf-8"></head><body><p>单击按钮将段落中的“blue”替换成“red”。</p><p id="demo">mr blue has a blue house and a blue car.</p><button onclick="myfunction()">点我</button><script>function myfunction(){ var str=document.getelementbyid("demo").innerhtml; var n=str.replace(/blue/gi,"red"); document.getelementbyid("demo").innerhtml=n;}</script></body></html>
javascript match() 方法
match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。
<!doctype html><html><head><meta charset="utf-8"></head><body><p id="demo">单击按钮显示matches</p><button onclick="myfunction()">点我</button><script>function myfunction(){ var str="the rain in spain stays mainly in the plain"; var n=str.match(/ain/g); document.getelementbyid("demo").innerhtml=n;}</script></body></html>
javascript search() 方法
search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。
如果没有找到任何匹配的子串,则返回 -1。
<!doctype html><html><head><meta charset="utf-8"></head><body><p id="demo">单击显示查找的位置</p><button onclick="myfunction()">点我</button><script>function myfunction(){ var str="mr. blue has a blue house" var n=str.search("blue"); document.getelementbyid("demo").innerhtml=n;}</script></body></html>
【相关推荐:javascript学习教程】
以上就是javascript中使用正则的方法有哪些的详细内容。
其它类似信息

推荐信息