js如何利用正则表达式截取指定长度字符串
1个回答
2018-09-06
展开全部
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"
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询