在给定索引上将字符串拆分为两个并返回两个部分 [英] split string in two on given index and return both parts

查看:110
本文介绍了在给定索引上将字符串拆分为两个并返回两个部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我需要在给定的索引上拆分,然后返回两个部分,用逗号分隔。例如:

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仅返回提取的字符串部分。
string.split只允许你拆分字符而不是索引
string.substring做我需要但只返回子串
string.substr非常相似 - 仍然只返回子串

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

推荐答案

试试这个

function splitValue(value, index) {
    return value.substring(0, index) + "," + value.substring(index);
}

console.log(splitValue("3123124", 2));

这篇关于在给定索引上将字符串拆分为两个并返回两个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆