Home > Web Front-end > JS Tutorial > body text

Write a simple regular method in JS

php中世界最好的语言
Release: 2018-03-29 14:58:07
Original
1422 people have browsed it

这次给大家带来在JS里编写简单的正则方式,在JS里编写正则方式的注意事项有哪些,下面就是实战案例,一起来看一下。

在字面量方式中,我们//之间包起来的所有的内容都是元字符,有的具有特殊意义,大部分都是代表本身含义的普通的元字符

var name = 'wo';
      var reg = /^\d+"+name+"\d+$/
Copy after login

为了解决上述想在正则里面加上一个变量这样的需求,我们只能使用实例创建的方式了

var reg = new RegExp("^\\d+"+name+"\\d+$","g")
Copy after login

字面量方式和实例创建的方式在正则中的区别?

1、字面量方式中出现的一切都是元字符,所以不能进行变量值的拼接,而实例创建的方式是可以的。

2、字面量中直接写\d就可以,而在实例中需要把它转译\\d

练习正则:

  1、年龄介于18-65  // 年龄介于18-19  20-59   60-65

 var reg = /^(1[8,9] | [2,5]\d | 6[0,5])$/
Copy after login

  2、验证邮箱的正则(简版)

  邮箱左边的规律:数字、字母、下划线、.、-  

var reg = /^[\w.-]+@[0-9a-zA-Z]+(\.[a-zA-Z]{2,4}){1,2}$/
Copy after login

  3、中国标准真实姓名 2-4位汉字

var reg = /^[\u4e00-\u9fa5]{2,4}$/
Copy after login

  4、身份证号码

 var reg = /^\d{17}(\d | x)$/
  var reg = /^\(d{2})(\d{4})(\d{4})(\d{2})(\d{2})(\d{2})(\d)(\d | X)$/
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

正则如何对C#进行校验

正则与Linux三大文本处理工具的使用详解

The above is the detailed content of Write a simple regular method in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!