Home  >  Article  >  Web Front-end  >  Regular expressions in js (2)

Regular expressions in js (2)

伊谢尔伦
伊谢尔伦Original
2016-11-22 14:29:55947browse

正则表达式对象的属性及方法
预定义的正则表达式拥有有以下静态属性:input, multiline, lastMatch, lastParen, leftContext, rightContext和$1到$9。其中input和multiline可以预设置。其他属性的值在执行过exec或test方法后被根据不同条件赋以不同的值。许多属性同时拥有长和短(perl风格)的两个名字,并且,这两个名字指向同一个值。(JavaScript模拟perl的正则表达式)
正则表达式对象的属性

属性含义$1...$9如果它(们)存在,是匹配到的子串$_参见input$*参见multiline$&参见lastMatch$+参见lastParen$`参见leftContext$''参见rightContextconstructor创建一个对象的一个特殊的函数原型global是否在整个串中匹配(bool型)ignoreCase匹配时是否忽略大小写(bool型)input被匹配的串lastIndex最后一次匹配的索引lastParen最后一个括号括起来的子串leftContext最近一次匹配以左的子串multiline是否进行多行匹配(bool型)prototype允许附加属性给对象rightContext最近一次匹配以右的子串source正则表达式模式lastIndex最后一次匹配的索引    


正则表达式对象的方法

方法含义compile正则表达式比较exec执行查找test进行匹配toSource返回特定对象的定义(literal representing),其值可用来创建一个新的对象。重载Object.toSource方法得到的。toString返回特定对象的串。重载Object.toString方法得到的。valueOf返回特定对象的原始值。重载Object.valueOf方法得到    

例子

<script language = "JavaScript">
var myReg = /(w+)s(w+)/;
var str = "John Smith";
var newstr = str.replace(myReg, "$2, $1");
document.write(newstr);
</script>

将输出"Smith, John"


Statement:
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