<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>正则表达式</title> </head> <body> <script> /*正则表达式可用于所有文本搜索和文本替换的操作。 * 语法: * /正则表达式主体/修饰符(可选) * */ // 一、search() 方法 // 此方法用于,检索字符串中指定的子字符串, // 或检索与正则表达式相匹配的子字符串, // 并返回检索到的第一个子串的起始下标。 // 1.search() 方法使用正则表达式 var str = "Visit Runoob Runoob!"; var n = str.search("Runoob"); console.log("n:", n); // n: 6 // 2.search() 方法使用字符串 str = "Visit Runoob Runoob!"; n = str.search("Runoob"); console.log("n:", n); // n: 6 // 二、replace() 方法 // 此方法用于在字符串中用一些字符替换另一些字符, // 或替换一个与正则表达式匹配的子串。 // 1.replace() 方法使用正则表达式 str = "Visit Microsoft Microsoft!"; var txt = str.replace(/microsoft/i,"Runoob"); console.log(txt); // Visit Runoob Microsoft! // 2.replace() 方法使用字符串 str = "Visit Microsoft Microsoft!"; txt = str.replace("Microsoft","Runoob"); console.log(txt); // Visit Runoob Microsoft! /*正则表达式修饰符 * i,忽略大小写。 * g,全局匹配。 * m,多行匹配。 * */ /*正则表达式模式 *方括号用于查找某个范围内的字符: *[abc],[0-9],(x|y)(或) * */ /*元字符是拥有特殊含义的字符: * \d 查找数字 * \s 查找空白字符。 * \b 匹配单词边界。 * \uxxxx 查找以十六进制数 xxxx 规定的 Unicode 字符。 * */ /*量词: * n+ 匹配任何包含至少一个 n 的字符串。 * n* 匹配任何包含零个或多个 n 的字符串。 * n? 匹配任何包含零个或一个 n 的字符串。 * */ /*使用 RegExp 对象 * 在 JavaScript 中,RegExp 对象是一个预定义了属性和方法的正则表达式对象。 * test() 方法是一个正则表达式方法。 * test() 方法用于检测一个字符串是否匹配某个模式, * 如果字符串中含有匹配的文本,则返回 true,否则返回 false。 * */ var patt1= new RegExp("e"); console.log(patt1.test("The best things in life are free")); // true console.log(/e/.test("The best things in life are free!")); // true /*使用 exec() exec() 方法是一个正则表达式方法。 exec() 方法用于检索字符串中的正则表达式的匹配。 该函数返回一个数组,其中存放匹配的结果。 如果未找到匹配,则返回值为 null。*/ console.log(/e/.exec("The best things in life are free")); // ["e", index: 2, input: "The best things in life are free", groups: undefined] </script> </body> </html>