Split a String by the Last Dot using JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

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 parameters we passed to the String.slice method are:

  1. start index - the index of the first character that should 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, whereas 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 a dot, because we want to exclude the dot from the new string.

If only a single parameter is passed to the method, it includes 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 does not 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.

If a dot is not contained in the string, the variables have an empty string value.

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee