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

Introduction to the use of JavaScript RegExp objects

jacklove
Release: 2018-05-07 10:00:04
Original
1508 people have browsed it

JavaScript RegExp 正则表达在验证表单等情况下运用频繁,所以本文详细的讲解正则的使用方法。

什么是 RegExp?

正则表达式描述了字符的模式对象。

当您检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp 就是这种模式。

简单的模式可以是一个单独的字符。

更复杂的模式包括了更多的字符,并可用于解析、格式检查、替换等等。

您可以规定字符串中的检索位置,以及要检索的字符类型,等等。

语法

var patt=new RegExp(pattern,modifiers);
Copy after login

或更简单的方法

var patt=/pattern/modifiers;
Copy after login

模式描述了一个表达式模型。

修饰符(modifiers)描述了检索是否是全局,区分大小写等。

注意:当使用构造函数创造正则对象时,需要常规的字符转义规则(在前面加反斜杠 \)。比如,以下是等价的:

var re = new RegExp("\\w+");var re = /\w+/;
Copy after login

RegExp 修饰符

修饰符用于执行不区分大小写和全文的搜索。

i - 修饰符是用来执行不区分大小写的匹配。

g - 修饰符是用于执行全文的搜索(而不是在找到第一个就停止查找,而是找到所有的匹配)。

实例 1

在字符串中不区分大小写找"runoob"

var str = "Visit RUnoob";var patt1 = /runoob/i;
Copy after login

以下标记的文本是获得的匹配的表达式:

Visit RUnoob

实例 2

全文查找 "is"

var str="Is this all there is?";var patt1=/is/g;
Copy after login

以下标记的文本是获得的匹配的表达式:

Is this all there is?

实例 3

全文查找和不区分大小写搜索 "is"

var str="Is this all there is?";var patt1=/is/gi;
Copy after login

以下 标记的文本是获得的匹配的表达式:

Is this all there is?

test()

test()方法搜索字符串指定的值,根据结果并返回真或假。

下面的示例是从字符串中搜索字符 "e" :

实例

var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free"));
Copy after login

由于该字符串中存在字母 "e",以上代码的输出将是:

true

当使用构造函数创造正则对象时,需要常规的字符转义规则(在前面加反斜杠 \)

实例

var re = new RegExp("\\w+");
exec()
Copy after login

exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。

下面的示例是从字符串中搜索字符 "e" :

实例 1

var patt1=new RegExp("e");document.write(patt1.exec("The best things in life are free"));
Copy after login

由于该字符串中存在字母 "e",以上代码的输出将是:

e

正则表达的使用较为广泛,本篇详细的讲解了正则的相关用法,想要观看更多的相关知识请关注php中文网。

相关推荐:

几个前端常见的JS排序代码

如何正确的使用JavaScript eval() 函数

关于jQuery stop() 的使用方法

The above is the detailed content of Introduction to the use of JavaScript RegExp objects. 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!