Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with limit, where last string contains the remainder

e.g. if I run this javascript:

var str = 'hello_world_there';
var parts = str.split('_', 2);

var p1 = parts[0];
var p2 = parts[1];

at the end, p1 contains "hello", and p2 contains "world".

I'd like p1 to contain "hello", and p2 to contain "world_there". i.e. I want p2 to contain the rest of the string, regardless of how many underscores it has (similar to how c#'s String.Split(char[] separator, int count) behaves.

Any workarounds ?

like image 298
Moe Sisko Avatar asked Aug 07 '14 07:08

Moe Sisko


People also ask

How do you get the last index of a split?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.

How do you split with delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

Does split return a string?

Using split()When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

How to split a string by the length of delimiter?

If you are given that the length of the delimiter is 1, then you can simply use a temp string to split the string. This will save the function overhead time in the case of method 2.

How to split text string where number comes after text?

The easiest way to split text string where number comes after text is this: To extract numbers, you search the string for every possible number from 0 to 9, get the numbers total, and return that many characters from the end of the string.

What is the use of split in Java?

In Java, split () is a method in String class. // expregexp is the delimiting regular expression; // limit is the number of returned strings public String [] split (String regexp, int limit); // We can call split () without limit also public String [] split (String regexp)

How do you split a list of strings in Python?

The split () method in Python returns a list of strings after breaking the given string by the specified separator. // regexp is the delimiting regular expression; // limit is limit the number of splits to be made str. split (regexp = "", limit = string.count (str))


Video Answer


1 Answers

For your specific case where you just want two parts, the simplest thing is indexOf and substring:

const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);

Live Example:

const text = "hello_world_there";
const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);
console.log(`p0 = "${p0}", p1 = "${p1}"`);

I've found I want that often enough I have it in a utility module:

const twoParts = (str, delim = " ") => {
    const index = str.indexOf("_");
    if (index === -1) {
        return [str, ""];
    }
    return [
        str.substring(0, index),
        str.substring(index + delim.length),
    ];
};

But if you wanted to do more than just teh two parts, an approach that doesn't require rejoining the string after the fact would be to use a regular expression with capture groups:

const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];

Live Example:

const text = "hello_world_xyz_there";
const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
console.log(`p0 = "${p0}", p1 = "${p1}", p2 = "${p2}"`);
like image 71
T.J. Crowder Avatar answered Oct 06 '22 01:10

T.J. Crowder