【发布时间】:2016-07-13 20:00:42
【问题描述】:
我正在尝试使用子字符串来区分 JavaScript 中的数据。 我要提取的原始数据是:
我使用的代码是
var contents = '0.! 3.0011632! \
0.01! 2.9417362! ';
var lastPosition = 0;
var count = 0;
//This code will continue looking for ! until it reaches three occurances
while (count < 3) {
//contents is a string variable that contains all data.
console.log(lastPosition);
console.log(contents.indexOf("!", lastPosition + 1));
console.log(contents.substr(lastPosition + 1, contents.indexOf("!", lastPosition + 1)));
lastPosition = contents.indexOf("!", lastPosition + 1);
count++;
}
问题是我得到的输出是:
0 //start
3 //end
0.! //#
3 //start
14 //end
3.0011632! //#
14 //start
23 //end
0.01! 2.9417362! //#
如您所见,它没有正确定位 !在第三个周期。这会随着更多数据继续下去,最终会开始丢失越来越多的!谁能告诉我我在这里做错了什么?
【问题讨论】:
-
你能解释一下'contents',或者更好的是,添加设置'contents'变量的代码吗?
-
contents 是一个包含所有数据的字符串。它有点大。
-
您的代码不会产生与您所说的相同的输出。那是真正的代码吗?
-
@evolutionxbox 拼写现在已修复,谢谢。我只使用了一个正则表达式来忽略java中字符组合的某些字符。你能在这里举一个例子,说明它如何分解字符串,这样我就可以撕掉单个数据点。谢谢。
-
我不是在说注解,字符串和位置不同。点击运行代码片段并查看。
标签: javascript string substring