Split string in jquery

Another method to get this would be to use a simple regex.

var str = "[email protected]";
var test = str.match(/(.+)\.(.+)/);

var filename = test[1];
var extension = test[2];

console.log(filename); 
console.log(extension); 

The regex uses capturing groups to group the data like you want. In my example, the capturing groups are the items surrounded by parentheses.

The regex is just grabbing the matching group 1 on everything before the last period, which corresponds to the filename. The second capturing group matches everything after the last period, and this corresponds to the extension.

If you wanted the extension to contain the period, you’d just modify the regex so that the last capturing group contains the period. Like so:

var str = "[email protected]";
var test = str.match(/(.+)(\..+)/);

Leave a Comment