JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string by the last dot in JavaScript?

To split a string by the last dot, you have to first get the index position of the last dot using the lastIndexOf() method.

Once you have the index position, call the slice() method to get the two substrings, one before the last dot and another after the last dot.

let str = "123.4567.89";

let index = str.lastIndexOf(".");
let before = str.slice(0, index);
console.log(before); //"123.4567"

let after = str.slice(index+1);
console.log(after); //"89"

str = "12,34.567";
index = str.lastIndexOf(".");

before = str.slice(0, index);
console.log(before); //"12,34"

after = str.slice(index+1);
console.log(after); //"567"

In JavaScript, string follows zero-based indexing. This means the first character is at the 0th index position, the second is at the 1st index position, and the last is at the (string.length -1) index position.

let str = "Pizza";
console.log(`First Character: ${str[0]}`); //"P"
console.log(`Second Character: ${str[1]}`); //"i"
console.log(`Last Character: ${str[str.length - 1]}`); //"a"

It is essential to understand that if a string does not include a dot, in that case, the lastIndexOf() method returns -1. So, it is recommended that you check the value returned by the lastIndexOf() method before calling the slice() method.

let str = "123,4567",
    before = "",
    after = "";

let index = str.lastIndexOf(".");

if(index !== -1){
  before = str.slice(0, index);
  after = str.slice(index+1);
}

console.log(before); //""
console.log(after); //""

You can see that the value returned by the lastIndexOf() method is -1.

Recommended Posts