Sometimes, we want to split a string at last occurrence of character then join with JavaScript.
In this article, we’ll look at how to split a string at last occurrence of character then join with JavaScript.
How to split a string at last occurrence of character then join with JavaScript?
To split a string at last occurrence of character then join with JavaScript, we can use some string methods.
For instance, we write:
const k = "ext.abc.jpg";
const l = `${k.substring(0, k.lastIndexOf("."))}-fx${k.substring(k.lastIndexOf("."))}`
console.log(l);
to call the substring
method to get the substring of k
between the first character and the index of the last occurrence of .
exclusive.
Then we call substring
with the last index of .
to the end of the string.
And then we combine them together in a template literal.
We used lastIndexOf
to get the index of the last .
.
Therefore, l
is 'ext.abc-fx.jpg'
.
Conclusion
To split a string at last occurrence of character then join with JavaScript, we can use some string methods.