Reputation: 1
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.
Upvotes: 0
Views: 136
Reputation: 13376
From the above comment ...
"How about something as simple as e.g. ...
'test-123-example'.split('-').slice(0,2).join('-')
... whichsplit
s, takes/slice
s the first two items and (re)join
s 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)
);
Upvotes: 1
Reputation: 370699
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 -
Upvotes: 0