Split string by first delimiter found

Viewed 76

I have a string with multiple delimiters and I wanted to split it by the first delimiter found. I couldn't find any method to do this every method I tried will return either all the char found after the last delimiter or the char between the first 2 delimiters found. How can I get all char after the first delimiter? Any help is appreciated. Thanks in advance.

x = 'aa-bb-cc-dd'
console.log(x.split('-')[1]) // returns bb expected bb-cc-dd

console.log(x.split('-').pop()) // returns dd expected bb-cc-dd

console.log(x.split('-')[1].pop()) // something like this but obviously this wont work

6 Answers

You can use String#indexOf with String#slice like this:

x = 'aa-bb-cc-dd'
console.log(x.slice(x.indexOf('-')+1)) // returns bb-cc-dd

How about using slice instead of split and then create a function which will return the expected value like this?

function splitting (str) {
    return str.slice(str.indexOf('-') + 1)
}

const r1 = splitting('aa-bb-cc-dd') // bb-cc-dd
const r2 = splitting(r1) // cc-dd
const r3 = splitting(r2) // dd

console.log(r1)
console.log(r2)
console.log(r3)

One way :

x = 'aa-bb-cc-dd'
function splitOnFirstDelimiter (str, del) {
  const index = str.indexOf(del);
  return index < 0 ? str : str.slice(index + del.length);
}
console.log(splitOnFirstDelimiter(x, '-'))

Don't "split" the string: use a Regex to match what you want (or don't want):

/^([^-]*)-?(.*)$/.exec( "aa-bb-cc-dd" )?.[2]

Which returns the expected result (bb-cc-dd) (or the entire string if no separator was found). And...

/^([^-]*)-?(.*)$/.exec( "aa-bb-cc-dd" )?.[1]

gives you the first group (aa)

May be too late, but :

var x = "aa-bb-cc-dd";
console.log(
  x.split("-").filter((e, i) => {
    return i != 0;
  }).join("-")
); // returns expected bb-cc-dd

It's a little inelegant looking, but you could use slice to take everything after the first split element and then join the array back together again:

x = 'aa-bb-cc-dd'
console.log(x.split('-').slice(1).join('-'))

Output:

bb-cc-dd

You could convert this into a simple function that used parameters to make this a lot more flexible:

function TakeAfter(source, delim, after) {
  return source.split(delim).slice(after).join(delim);
}

console.log(TakeAfter('aa-bb-cc-dd', '-', 1));
console.log(TakeAfter('aa-bb-cc-dd', '-', 2));
console.log(TakeAfter('aa-bb-cc-dd', '-', 3));

Note: You should add bound checking into this.

Related