Home > Back-end >  Split string to only return the substring prior to the nth occurrence of a delimiter in JavaScript
Split string to only return the substring prior to the nth occurrence of a delimiter in JavaScript

Time:11-08

Is there a way in Java script to return just the substring prior to the nth occurrence of a delimiter?

For example:

If I have a string "test-123-example" and want to only return the substring before the second instance of "-", resulting in just "test-123", is there a way to do that in one line?

I have tried using the split() function using ("-") and using indexOf() to find the second "-", but having no luck.

CodePudding user response:

Instead of splitting, match with a regular expression to get non-dashes, followed by a dash, followed by more non-dashes.

const input = "test-123-example";
const result = input.match(/[^-] -[^-] /)[0];
console.log(result);

  • [^-] - Any character but a -
  • [^-] - One or more characters that aren't -
  • - - A literal -
  • [^-] - One or more characters that aren't -

CodePudding user response:

From the above comment ...

"How about something as simple as e.g. ... 'test-123-example'.split('-').slice(0,2).join('-') ... which splits, takes/slices the first two items and (re)joins them again?"

console.log(
  'test-123-example'
    .split('-')
    .slice(0, 2)
    .join('-')
);

From the above example code the OP then could implement a generic approach in order to ... " return the substring prior to the nth occurrence of a delimiter".

function getSubstringPriorToNthDelimiter(
  value, delimiter = '-', nthCount = 2
) {
  return String(value)
    .split(String(delimiter))
    .slice(0, Number(nthCount))
    .join(String(delimiter));
}

console.log(
  getSubstringPriorToNthDelimiter('test-123-example')
);
console.log(
  getSubstringPriorToNthDelimiter('test_123_456_text', '_')
);
console.log(
  getSubstringPriorToNthDelimiter('test_123_456_text', '_', 3)
);

  • Related