Reputation: 335
I want to split a string in jquery. My string is a filename. I want to split the filename to get the extension. What I am facing is my filename contains any dot then I can't get the extension.
I had tried like this:
var str = "[email protected]";
var test = str.split(".");
console.log(test);
What I want is test[0] = "[email protected]"
and test[1] = jpg
.
Upvotes: 11
Views: 84432
Reputation: 1404
var str = "[email protected]";
var test = str.split(".");
var extension = test[test.length - 1];
var filename = str.replace("."+extension,"");
Upvotes: 7
Reputation: 1482
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(/(.+)(\..+)/);
Upvotes: 9
Reputation: 5179
Use lastIndexOf
with the dot to slice the string into two parts:
var str = "[email protected]";
var index = str.lastIndexOf(".");
var test = [str.slice(0, index), str.slice(index+1)];
console.log(test[0], test[1]);
Upvotes: 0
Reputation: 4032
In your spitted array the extension index is obviously last position.
So after using split function it will return an array. You should just get last index position element from array using this:
var str = "[email protected]";
var test = str.split(".");
console.log(test[test.length-1]);
//OR
console.log(test.pop());
Upvotes: 0
Reputation:
Try this :
var data = $('#date').text();
var arr = data.split('/');
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);
For more details you can visit : How to split the string using jQuery or javascript?
Upvotes: 6
Reputation: 15256
The JavaScript split() function splits a string into an array of strings where the split occurs at the specified delimiter. What you are looking for is the last element of that array. So, for example:
var temp = str.split(".");
var test = temp[temp.length - 1];
will result in test containing the entry you desire.
A more efficient solution might also be:
var test = str.split('.').pop();
See also:
http://www.w3schools.com/jsref/jsref_split.asp
It also appears that this is frequently asked question. See:
How can I get file extensions with JavaScript?
Upvotes: 2