首页 > 语言 > JavaScript > 正文

JavaScript正则表达式简单实用实例

2024-05-06 15:15:28
字体:
来源:转载
供稿:网友

 1.replace

var user='xia&&min**';user=user.replace(/[^A-Za-z/d_-]+/,'');   //需要再次赋值console.log(user); //xiamin**user = user.replace(/[^A-Za-z/d_-]+/g, '');  //全局进行替换console.log(user); //xiamin

分割邮件

var email='nettuts@tutsplus.com';var result=email.replace(/([A-Za-z_/d-]+)@([A-Za-z_/d-]+)/.[a-z]{2,4}/ig,'$1,$2');console.log(result); //nettuts tutsplus

2.test

这个方法接受单个字符串参数,然后返回一个布尔值,该值表明是否找到一个批评。如果你不需要对特定的匹配结果进行操作,比如,验证用户名,“test”方法已足够完成这个任务。

var name='xiamin';var result=/[A-Za-z-_]+/.test(name);console.log(result);

3.match

与test方法不同,match() 返回一个包含所有找到的批评的数组。

var name='xiamin';var result=name.match(/i/g);console.log(result); //(2) ["i", "i"]

匹配所有问号前后内容

var url ='http://localhost:8080?name=xiamin';var result=url.match(/^(.+)/?(.+)/i);console.log(result);//"http://localhost:8080?name=xiamin?" "http://localhost:8080" "name=xiamin"

匹配#后面的内容

var url ='http://localhost:8080?name=xiamin#dnsjdnw';var result=url.match(/#(.+)/i);console.log(result);//"#dnsjdnw", "dnsjdnw"

获取协议

var url ='http://localhost:8080?name=xiamin#dnsjdnw';var result=url.match(/(ht|f)tps?:/i);console.log(result);//"http:", "ht"

匹配页面url

var url ='http://www.baidu.com';var result=url.match(/.+/.[a-z]{2,4}/ig);console.log(result);//http://www.baidu.com

以上所述是小编给大家介绍的JavaScript正则表达式简单实用实例,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对错新站长站网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选