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
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.
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.
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.
Try this
function split_at_index(value, index) { return value.substring(0, index) + "," + value.substring(index); } console.log(split_at_index('3123124', 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With