js如何使用正则表达式

2025-04-24 09:55:37

1、replace()替换目标字符串,在一稍僚敉视个长串中替换子串为另外一个字符串。代码如下:<!DOCTYPE html><html><head><m髫潋啜缅eta charset="utf-8"><title>Test re in js</title></head><body><p>repalce String:"js"</p><p>Where is the js!</p><p id="position"></p><button onclick="myFunction()">Search</button><script>function myFunction() { var str="Where is the js!"; var target="js"; var pattern="baidu"; var pos=str.replace(target,pattern); document.getElementById("position").innerHTML=pos;}</script></body></html>

js如何使用正则表达式
js如何使用正则表达式
js如何使用正则表达式

2、search()寻找目标字符串(target)返回并下标。

js如何使用正则表达式
js如何使用正则表达式
js如何使用正则表达式

3、test()用于测试模式串是否存在于目标字腿发滏呸符串中,是返回true,否返回false代码如下:<!DOCTYPE html><html><head媪青怍牙><meta charset="utf-8"><title>Test re in js</title></head><body><p>Is :"js" in the text behind.</p><p>Where is the js!</p><p id="position"></p><button onclick="myFunction()">Search</button><script>function myFunction() { var str="Where is the js!"; var pattern=/js/; var result=pattern.test(str); document.getElementById("position").innerHTML=result;}</script></body></html>

js如何使用正则表达式
js如何使用正则表达式
js如何使用正则表达式

4、exec()用于搜索字符匹配返回字符,不存在返回null代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>Test re in js</title></head><body><p>Is :"java" in the text behind.</p><p>Where is the js!</p><p id="position"></p><button onclick="myFunction()">Search</button><script>function myFunction() { var str="Where is the js!"; var pattern=/j/; var result=pattern.exec(str); document.getElementById("position").innerHTML=result;}</script></body></html>

js如何使用正则表达式
js如何使用正则表达式

5、如下是正则表达式的参数:

js如何使用正则表达式
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢