2f34435-something.jpg
4t44234-something.jpg
5465g67-something.jpg
says I have 3 string above, without using split, how can I do regex to get the value before dash? the length of strings is not consistent though..
One option would be to match one or more non-dash characters at the beginning of the string:
^[^-]+
^ - Anchor that denotes the beginning of the string[^-] - Character set to match all characters that are not dashes.+ - One or more occurrences of non-dash characters.For instance:
'2f34435-something.jpg'.match(/^[^-]+/);
// ["2f34435"]
With the .split() method, you would just need to retrieve the first match:
'2f34435-something.jpg'.split('-')[0];
// "2f34435"
you can use...
/^(.+?)-/gm
which will capture all 3 ( or as many as you have )
You can see it in action here https://regex101.com/r/gD5sU2/2
This will also handle if you get - in the rest of the filename...
such as :-
2f34435-something-else.jpg
4t44234-something.jpg
5465g67-something.jpg
^ is not required.
str.substring(0, str.indexOf('-'));