[英]Using array returned by String.split
data = 'numbersXXXtext';
or 要么
data = 'XXXtext';
var get = data.split('XXX');
var sum = get[1];
I would like get always "text". 我想永远“文本”。 If
data
equals numbersXXXtext
, the code works fine, but if data
is XXXtext
then get[1]
is undefinded. 如果
data
等于numbersXXXtext
,代码工作正常,但如果data
是XXXtext
则get[1]
未定。
Does anyone know how I can solve this? 有谁知道我怎么解决这个问题?
If there is only one occurrence of XXX
in the string, the bit you want will always be the last item in the array returned by split
. 如果字符串中只出现一次
XXX
,则所需的位将始终是split
返回的数组中的最后一项。 You can use pop
to get the last item of an array: 您可以使用
pop
来获取数组的最后一项:
var a = "numbersXXXtext";
var b = "XXXtext";
console.log(a.split('XXX').pop()); // "text"
console.log(b.split('XXX').pop()); // "text"
尝试这个:
var sum = get.length > 1 ? get[1] : get[0]
Strange, i just tried your code, and it's working. 奇怪,我只是尝试了你的代码,它正在运作。 ( http://writecodeonline.com/javascript/ ) Are you sure you are not missing something?
( http://writecodeonline.com/javascript/ )你确定你没有遗漏什么吗?
data = 'numbersXXXtext';
//data = 'XXXtext';
var get = data.split('XXX');
document.write(get[1]);
document.write("</br>");
document.write(get);
document.write("</br>");
I didn't get undefined in neither of your strings 我的两个字符串都没有被定义
An alternative using substring: 使用子字符串的替代方法:
var data = 'numbersXXXtext';
var value = data.substring(data.indexOf('XXX') + 'XXX'.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.