How to split a string by the last dot using JavaScript

Split a String by the Last Dot using JavaScript

The topic of this article will be about how you can split a string by the last dot using JavaScript. Some methods you can refer to in the article like using split() with regex or using slice() method.

Split a string by the last dot using JavaScript 

Using split() with regex

A string item’s parted technique partitions the string into various substrings and returns the new cluster. If the parameter is the empty string “,” the string will be divided in half. In addition to the method’s parameters, here is how to write it.

Syntax:

string.split(separator, limit)

Parameters:

  • separator: Specifies the character, or regular expression, to split the string. If omitted, the entire string is returned (an array with only one item).
  • limit: An integer specifying the number of splits. Items after the division limit will not be included in the array.

When we use the split() method with the string to split and pass the regex definition for how to split the string, we will get the following result:

Code:

var splitString = "842.344.learnshareit".split(/\.(?=[^\.]+$)/);
console.log(splitString[1]);

Output:

"learnshareit"

By using regex, we can define for the program to know at what point the string should be split, specifically here at the last dot. The return value on our console will be the number after this dot. Or you can also refer to the method below.

Using slice() method

The slice() method is used to get (extract) part of the array. We can use this method with an array to get the value at any position, so first, we need to find the position of the last “.” by using the lastIndexOf() method and passing it a dot character parameter.

Code:

var splitString = "842.344.learnshareit".split(/\.(?=[^\.]+$)/);
var index = splitString.lastIndexOf(".");
var after = splitString.slice(index + 1);
console.log(after[1]);

Like the code above, we use the slice() method to slice the string into a two-valued array consisting of the part before the last dot and the part after it. We need to print the element value with an index of 1 to have the same result as the first way.

Summary

To summarize, we have gone through two ways to split a string by the last dot using JavaScript. Split() with regex will be much more compact, but you must understand how to custom regex.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *