How to Get the Substring Before a Character in JavaScript
Recently, I had to manipulate a string to obtain information that followed a certain structure.
The example below is similar to what I had to do.
I wanted to get name, which was followed by a colon :.
let str = "name: description";
There were a few ways I could’ve gone about this.
Using split()
str = str.split(":")[0];
In str.split(":"), the parameter acts as a delimiter in the string, and each element is returned inside an array.
For the string above, the result is:
["name", " description"]
This is why I am accessing the zeroth element.
Using substring() and indexOf()
str = str.substring(0, str.indexOf(":"));
str.indexOf(":") returns 4, so we are obtaining the string from index 0 (inclusive) to 4 (exclusive).
Using regex
str = /(.+):/.exec(str)[0];
(.+) matches any number of word characters.
: matches, well, a colon.