javascript 在给定的索引上将字符串分成两部分并返回两部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16441770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
split string in two on given index and return both parts
提问by Mike Rifgin
I have a string that I need to split on a given index and then return both parts, seperated by a comma. For example:
我有一个字符串,我需要在给定的索引上拆分它,然后返回两个部分,用逗号分隔。例如:
string: 8211 = 8,211
98700 = 98,700
So I need to be able to split the string on any given index and then return both halves of the string. Built in methods seem to perform the split but only return one part of the split.
所以我需要能够在任何给定的索引上拆分字符串,然后返回字符串的两半。内置方法似乎执行拆分但只返回拆分的一部分。
string.slice only return extracted part of the string. string.split only allows you to split on character not index string.substring does what I need but only returns the substring string.substr very similar - still only returns the substring
string.slice 只返回字符串的提取部分。string.split 只允许你拆分字符而不是索引 string.substring 做我需要的但只返回子字符串 string.substr 非常相似 - 仍然只返回子字符串
回答by Chamika Sandamal
Try this
试试这个
function splitValue(value, index) {
return value.substring(0, index) + "," + value.substring(index);
}
console.log(splitValue("3123124", 2));
回答by Alan R. Soares
ES6 1-liner
ES6 1-班轮
// :: splitAt = number => Array<any>|string => Array<Array<any>|string>
const splitAt = index => x => [x.slice(0, index), x.slice(index)]
console.log(
splitAt(1)('foo'), // ["f", "oo"]
splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]
)
回答by NullPointerException
You can also use number formatter JS available at
您还可以使用数字格式化程序 JS
https://code.google.com/p/javascript-number-formatter/
https://code.google.com/p/javascript-number-formatter/
http://jsfiddle.net/chauhangs/hUE3h/
http://jsfiddle.net/chauhangs/hUE3h/
format("##,###.", 98700)
format("#,###.", 8211)
回答by Nathan
Something like this?...
这种东西?...
function stringConverter(varString, varCommaPosition)
{
var stringArray = varString.split("");
var outputString = '';
for(var i=0;i<stringArray.length;i++)
{
if(i == varCommaPosition)
{
outputString = outputString + ',';
}
outputString = outputString + stringArray[i];
}
return outputString;
}
回答by devashish-patel
You can also do it like this.
https://jsfiddle.net/Devashish2910/8hbosLj3/1/#&togetherjs=iugeGcColp
你也可以这样做。
https://jsfiddle.net/Devashish2910/8hbosLj3/1/#&togetherjs=iugeGcColp
var str, result;
str = prompt("Enter Any Number");
var valueSplit = function (value, length) {
if (length < 7) {
var index = length - 3;
return str.slice(0, index) + ',' + str.slice(index);
}
else if (length < 10 && length > 6) {
var index1, index2;
index1 = length - 6;
index2 = length - 3;
return str.slice(0,index1) + "," + str.slice(index1,index2) + "," + str.slice(index2);
}
}
result = valueSplit(str, str.length);
alert(result);
回答by i336_
If code elegance ranks higher than the performance hit of regex, then
如果代码优雅的排名高于正则表达式的性能影响,那么
'1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
=> "1234,567"
There's a lot of room to further modify the regex to be more precise.
有很多空间可以进一步修改正则表达式以使其更精确。
If join()
doesn't work then you might need to use map
with a closure, at which point the other answers here may be less bytes and line noise.
如果join()
不起作用,那么您可能需要使用map
闭包,此时此处的其他答案可能会减少字节和线路噪音。
回答by vcygni
function splitText(value, index) {
if (value.length < index) {return value;}
return [value.substring(0, index)].concat(splitText(value.substring(index), index));
}
console.log(splitText('this is a testing peace of text',10));
// ["this is a ", "testing pe", "ace of tex", "t"]
For those who want to split a text into array using the index.
对于那些想要使用索引将文本拆分为数组的人。
回答by lonewarrior556
You can easily expand it to split on multiple indexes, and to take an array or string
您可以轻松扩展它以拆分多个索引,并采用数组或字符串
const splitOn = (slicable, ...indices) =>
[0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));
splitOn('foo', 1);
// ["f", "oo"]
splitOn([1, 2, 3, 4], 2);
// [[1, 2], [3, 4]]
splitOn('fooBAr', 1, 4);
// ["f", "ooB", "Ar"]
lodash issue tracker: https://github.com/lodash/lodash/issues/3014
lodash 问题跟踪器:https: //github.com/lodash/lodash/issues/3014