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.
str = str.split(":");
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.
str = str.substring(0, str.indexOf(":"));
4, so we are obtaining the string from index
0 (inclusive) to
str = /(.+):/.exec(str);
(.+) matches any number of word characters.
: matches, well, a colon.
Revise the code and make it more robust with proper test case and check an error there before implementing into a production environment.
If you need help at any point, please send me a message and I will do my best to assist you.