最残酷的事情!下面的代码打印出'llo'而不是预期的'wo'。我得到了一些其他数字这样令人惊讶的结果。我在这里错过了什么?javascript子字符串
alert('helloworld'.substring(5, 2));
最残酷的事情!下面的代码打印出'llo'而不是预期的'wo'。我得到了一些其他数字这样令人惊讶的结果。我在这里错过了什么?javascript子字符串
alert('helloworld'.substring(5, 2));
你混淆substring()
和substr()
:substring()
预计两项指标,而不是偏移量和长度。在你的情况下,索引是5和2,即字符2..4将被返回,因为更高的索引被排除。
检查substring
syntax:
子(从,到)
从必需。 开始提取的索引。第一个字符 位于索引0
到可选。该索引 在哪里停止提取。如果忽略 ,它提取 字符串的其余部分
我会给予你这有点奇怪。我自己不知道。
你想要做什么是
alert('helloworld'.substring(5, 7));
alert('helloworld'.substring(5, 2));
上面的代码是错误的,因为第一个值是起点,从焦炭5是o
结束point.Eg移动和去为char 2这是l
所以会得到所以你已经告诉它倒退。
昱欧想要的是
alert('helloworld'.substring(5, 7));
见下面的语法:
str.substring(indexA, [indexB])
如果indexA > indexB
,在substring()
功能行为,如果论点相反。
这里要考虑的文档: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
您在JavaScript中的三个选项:
//slice
//syntax: string.slice(start [, stop])
"Good news, everyone!".slice(5,9); // extracts 'news'
//substring
//syntax: string.substring(start [, stop])
"Good news, everyone!".substring(5,9); // extracts 'news'
//substr
//syntax: string.substr(start [, length])
"Good news, everyone!".substr(5,4); // extracts 'news'
这是我做了什么,
var stringValue = 'Welcome to India';
// if you want take get 'India'
// stringValue.substring(startIndex, EndIndex)
stringValue.substring(11, 16); // O/p 'India'
+1提SUBSTR。 – 2010-01-01 16:58:22