随笔2

关于js中的正则表达式RegExp

RegExp是中的一个对象,可以通过new来定义一个新的正则表达式对象;

定义

直接定义:/pattern/attributes
创建对象的语法:new RegExp(pattern, attributes)

参数

pattern 是一个字符串,指定了正则表达式的模式或其他正则表达式。
attributes 是一个可选的字符串,包含属性 “g”、”i” 和 “m”,分别用于指定全局匹配、区分大小写的匹配和多行匹配。

可用的方法:
  • test()方法检索指定值,返回true或false
var a = new RegExp('a')
a.test('haha') = true
a.test() = true
a.test(undefined) = true
a.test('') = false
a.test(null) = false
  • exec() 方法检索字符串中的指定值,返回一个数组
var a = new RegExp('con')
a.exec('contact') = ["con", index: 0, input: "contact", groups: undefined]
a.exec('hhh') = null
a.exec(null) = null
a.exec() = null
//在定义正则对象的时候,还可以添加第二个参数'g',即找出字符串中全部符合的字符
var patt1=new RegExp("e","g");
do
{
    result=patt1.exec("The best things in life are free");
    document.write(result);
}
while (result!=null) 
//eeeeeenull
  • compile()方法,对正则表达式进行编译
var a = new RegExp('a')
a.complie() = /a/
String 对象支持正则表达式的方法:
  • search 检索于正则表达式匹配的值,返回第一个与目标字符相匹配的起始位置
var string = 'telephone'
string.search(/ph/) = 4
string.search(/haha/) = -1
string.search(/PH/) = -1
string.search(/PH/i) = 4//添加i参数,表示不区分大小写
  • match 找到一个或多个正则表达式的匹配
var string = 'strawberry'
string.match(/str/) = ["str", index: 0, input: "strawberry", groups: undefined]
string.match(/ST/i) = ["st", index: 0, input: "strawberry", groups: undefined]
string.match(/haha/) = null
string.match(/r/g) = ["r", "r", "r"]
  • replace 替换于正则表达式匹配的子串
var str = 'if you want to go, i new the reason is simple'
str.replace(/want/, 'wanna') = 'if you wanna to go....'
string.replace(/o/g, '0') = 'if y0u want t0 g0, ....)

var str2 = 'HhHh'
str2.replace(/h/gi, 'a') = aaaa
  • split 把字符串分割为字符串数组
var string = 'hello'
string.split(/h/) = ["", "ello"]

详情见 http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp

关于JavaScript中的几个全局函数
  • eval()
    可计算某个字符串,并执行其中的的 JavaScript 代码。
eval('2+2') = 4
var x = 10
eval('x*10') = 100
  • Number()
    可以把对象转换成数字,如果是date类型那么结果为1970年到当前的毫秒数如果无法转换则返回NaN
Number(false) = 0
var a = new Boolean(true)
Number(a) = 1
  • String()
    把对象值转换为字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值