Split a String by the Last Dot using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Split a String by the last Dot in JavaScript #

To split a string by the last dot, call the lastIndexOf() method to get the last index of a dot in the string and use the slice() method to get two substrings - one including the characters before the last dot, and the other - the characters after the last dot.

index.js
const str = '3.14.17'; const index = str.lastIndexOf('.'); console.log(index); // 👉️ 4 const before = str.slice(0, index); console.log(before); // 👉️ "3.14" const after = str.slice(index + 1); console.log(after); // 👉️ "17"

We used the String.lastIndexOf method to get the index of the last occurrence of a dot in the string.

The two arguments we passed to the String.slice method are:

  1. start index - the index of the first character to be included in the new string
  2. end index - go up to, but not including this character

To get the part before the last dot, we start at index 0 and go up to, but not including the index of the last dot.

Indexes are zero-based in JavaScript. The index of the first character in a string is 0, and the index of the last character is string.length - 1.

We only provided a start index in the second call to the slice method. We added 1 to the last index of the dot because we want to exclude the dot from the new string.

When passed a single argument, slice returns the characters to the end of the string.

The lastIndexOf method returns -1 if the supplied substring is not contained in the string.
index.js
console.log('314'.lastIndexOf('.')); // 👉️ -1

If you need to handle a scenario where the string doesn't contain a dot, you can use an if statement.

index.js
const str = '314'; const index = str.lastIndexOf('.'); // 👉️ -1 let before = ''; let after = ''; if (index !== -1) { before = str.slice(0, index); after = str.slice(index + 1); } console.log(before); // 👉️ "" console.log(after); // 👉️ ""
We only reassign the before and after variables if a dot is contained in the string.

The if block doesn't run if a dot is not contained in the string.

This helps us avoid a scenario where we pass -1 as a parameter to the slice method and get unexpected results.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.