js如何利用正则表达式截取指定长度字符串

JavaScript014

js如何利用正则表达式截取指定长度字符串,第1张

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"

开头和结束符不需要吧,把^和$删掉,你两个尖括号直接用就行了,加方括号干嘛。而且.*只会匹配最多的字符,所以这样写并不会匹配C或G,而会匹配第一个和最后一个尖括号,你用.*?试一试。所以我觉得用<(.*?)>就行了。仅供参考