[英]Javascript: Trim the length of string in an array
I would like to ask if it is possible to trim the length of multiple strings in an array in javascript. 我想问问是否有可能在javascript中修剪多个字符串的长度。 The length of each string of my array is different, however I would like to trim the last 2 digit (meaning trimming "-2") for each of them.
我的数组中每个字符串的长度都不同,但是我想为它们中的每一个修剪最后2位数字(意思是修剪“ -2”)。
var array = ["517577144-2","503222534-2","100003527692828-2","654703438-2","4205501-2"]
Cheers, Karen 干杯,凯伦
map function: 地图功能:
array = array.map(function(d){return d.substr(0,d.length-2)});
or you can use slice method inside: 或者您可以在内部使用slice方法:
array = array.map(function(d){return d.slice(0,-2)});
另一个选择是您可以将map与slice函数一起使用:
array = array.map(function(str){return str.slice(0,str.length-2)});
Look at the 'map' function. 查看“地图”功能。 This should do it for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
这应该为您做到: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
You can try like this: 您可以这样尝试:
var x;
for(x = 0; x < 10; x++)
{
array[x] = array[x].replace('-2', '');
}
This will remove the last character -2
in the array. 这将删除数组中的最后一个字符
-2
。
array = array.map(function(item) {
return item.replace('-2', '');
})
If you want to remove any character which is at the last not specifically -2
then 如果要删除最后一个不是特别是
-2
字符,则
array = array.map(function(item) {
return item.substr(0, item.length-2);
})
Multiple ways to trim last two characters: substr
, substring
, replace
or slice
(cleanest solution). 修剪后两个字符的多种方法:
substr
, substring
, replace
或slice
(最干净的解决方案)。
var array = ["517577144-2","503222534-2","100003527692828-2","654703438-2","4205501-2"]; // Using substr method var trimmed = array.map(function(item) { return item.substr(0,item.length - 2); }); log(trimmed); // Using substring method trimmed = array.map(function(item) { return item.substring(0,item.length - 2); }); log(trimmed); // Using regular expression in replace method trimmed = array.map(function(item) { return item.replace(/.{2}$/,''); }); log(trimmed); // Using slice method trimmed = array.map(function(item) { return item.slice(0,-2); }); log(trimmed); function log(array) { document.write('<pre>' + JSON.stringify(array, null, 2) + '</pre>'); }
Instead of map you can always use a standard for
loop too. 除了地图,您也可以始终使用标准的
for
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.