因此,一个子字符串可以有两个参数,开始的索引和停止的索引,如下所示
var str="Hello beautiful world!";
document.write(str.substring(3,7));
但是,有没有一种方法可以将起始点和结束点指定为一组要抓取的字符,所以我希望它不是起始点是3,而是"lo“,而不是结束点是7,所以我希望它是"wo”,这样我就会抓取"lo but wo“。有没有一个Javascript函数已经可以达到这个目的了?
发布于 2012-12-15 04:56:02
听起来您想使用正则表达式和string.match()来代替:
var str="Hello beautiful world!";
document.write(str.match(/lo.*wo/)[0]); // document.write("lo beautiful wo");
注意,match()返回一个匹配数组,如果没有匹配,该数组可能为null。因此,您应该包括null检查。
如果您不熟悉正则表达式,这是一个很好的资源:http://www.w3schools.com/jsref/jsref_obj_regexp.asp
发布于 2012-12-15 04:52:06
使用方法indexOf
:
document.write(str.substring(3,str.indexOf('wo')+2));
发布于 2012-12-15 04:54:03
是的,你可以用正则表达式很容易做到这一点:
var substr = /lo.+wo/.exec( 'Hello beautiful world!' )[0];
console.log( substr ); //=> 'lo beautiful wo'
https://stackoverflow.com/questions/13889390
复制相似问题