Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string in two on given index and return both parts

Tags:

javascript

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

like image 608
Mike Rifgin Avatar asked May 08 '13 13:05

Mike Rifgin


People also ask

Can you split a string at an index?

To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string.

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

How do you split a string by index in Python?

In Python, strings can be broken and accessed using a split() function, which splits the given string according to the specified separator or by default separator as whitespace. This function returns the array of strings, so as earlier in Python array can be accessed using indexing.


1 Answers

Try this

function split_at_index(value, index) {  return value.substring(0, index) + "," + value.substring(index); }  console.log(split_at_index('3123124', 2));
like image 52
Chamika Sandamal Avatar answered Sep 27 '22 18:09

Chamika Sandamal