dot*_*tty 20 javascript string split
说,我有一个字符串
"hello is it me you're looking for"
Run Code Online (Sandbox Code Playgroud)
我想删除这个字符串的一部分并返回新字符串,类似于
s = string.cut(0,3);
Run Code Online (Sandbox Code Playgroud)
s现在等于:
"lo is it me you're looking for"
Run Code Online (Sandbox Code Playgroud)
编辑:它可能不是从0到3.它可能是5到7.
s = string.cut(5,7);
Run Code Online (Sandbox Code Playgroud)
会回来的
"hellos it me you're looking for"
Run Code Online (Sandbox Code Playgroud)
Jak*_*ake 32
你快到了.你想要的是:
http://www.w3schools.com/jsref/jsref_substr.asp
所以,在你的例子中:
Var string = "hello is it me you're looking for";
s = string.substr(3);
Run Code Online (Sandbox Code Playgroud)
因为只提供一个开始(第一个arg)从该索引到字符串的结尾.
更新,如下:
function cut(str, cutStart, cutEnd){
return str.substr(0,cutStart) + str.substr(cutEnd+1);
}
Run Code Online (Sandbox Code Playgroud)
使用
功能
返回一个索引与另一个索引之间或字符串末尾的字符串子集.
substring(indexA, [indexB]);
Run Code Online (Sandbox Code Playgroud)
指数A
An integer between 0 and one less than the length of the string.
Run Code Online (Sandbox Code Playgroud)
indexB (可选)0到字符串长度之间的整数.
substring从indexA中提取字符,但不包括indexB.特别是:
* If indexA equals indexB, substring returns an empty string.
* If indexB is omitted, substring extracts characters to the end
of the string.
* If either argument is less than 0 or is NaN, it is treated as if
it were 0.
* If either argument is greater than stringName.length, it is treated as
if it were stringName.length.
Run Code Online (Sandbox Code Playgroud)
如果indexA大于indexB,那么substring的效果就好像交换了两个参数; 例如,str.substring(1,0)== str.substring(0,1).
其他一些更现代的替代方案是:
分裂和加入
function cutFromString(oldStr, fullStr) {
return fullStr.split(oldStr).join('');
}
cutFromString('there ', 'Hello there world!'); // "Hello world!"
Run Code Online (Sandbox Code Playgroud)
改编自MDN 示例
String.replace(),它使用正则表达式。这意味着它可以更加灵活地区分大小写。
function cutFromString(oldStrRegex, fullStr) {
return fullStr.replace(oldStrRegex, '');
}
cutFromString(/there /i , 'Hello THERE world!'); // "Hello world!"
Run Code Online (Sandbox Code Playgroud)