Javascript 字符串上的方法(性能好)
var str = "It's a long string."var length = 10
console.log( str.slice( 0, length ) ) // "It's a lon"
用正则(match)
var str = "It's a long string."var length = 10
var regExp = new RegExp( "^(.{0," + length + "}).*$" ) // /^(.{0,10}).*$/
console.log( str.match( regExp )[ 1 ] ) // "It's a lon"
用正则(replace)
var str = "It's a long string."var length = 10
var regExp = new RegExp( "^(.{0," + length + "}).*$" ) // /^(.{0,10}).*$/
console.log( str.replace( regExp, "$1" ) ) // "It's a lon"
错了好几个地方啊,第一:正则不是全局的,第二:返回的数组中,第一组(下标为 0 的)为整个正则匹配的结果,第三:js 的正则在匹配成功后就返回,后面的要再次调用!
var str = 'ssssss w11112131 sssss w22222 asssssssss w33333 sssssssss'var p = /w\d*/g
var s = [], m
while(m = p.exec(str)){
s.push(m[0])
}
alert("===" + s[0] + "===" + s[1] + "===" + s[2] + "===")
var str = "BEGIN CONST a,b=10,c END IF a>10 && (a+c<20 || b>c) THEN RETURN true END ELSE RETURN false END END END"str=str.replace(/\s/g,"")//取掉空格
str=str.match(/IF(\S*)THEN/)[1]//正则取出IF和THEN之间的字符串
str=str.split("&&")//按照&&分组
var str_end=str[0].split('>') //按照>分组
alert(str_end)//最终结果为str_end[0]=a str_end[1]=10