One way to remove part of a string before a colon is to use the JavaScript string’s substring
method.
For instance, we can write:
const str = "Abc: Lorem ipsum sit amet";
const newStr = str.substring(str.indexOf(":") + 1);
console.log(newStr)
We use the indexOf
method to get the index of the first colon.
Then we add 1 to that pass that into substring
to get the substring after the first colon.
Therefore, newStr
is 'Lorem ipsum sit amet’
.
Use the Array.prototype.split and Array.prototype.pop Methods
Another way to remove the part of a string before the colon is to use the JavaScript array’s split
and pop
methods.
To do this, we write:
const str = "Abc: Lorem ipsum sit amet";
const newStr = str.split(":").pop();
console.log(newStr)
We call split
on str
to split str
into an array using the colon as the delimiter.
Then we call pop
to return the last element of the array returned by split
.
And so we get the same result as before.
Use a Regex
We can also use a regex to split a string by a given delimiter and get the part we want from the split string.
For instance, we can write:
const str = "Abc: Lorem ipsum sit amet";
const newStr = /:(.+)/.exec(str)[1];
console.log(newStr)
to call exec
on the regex that matches the colon separator.
And we use index 1 to get the 2nd item from the split string.
And so we get the same result as before.