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
.
JQuery's library contains the function split() that is utilized to separate a string into an array. One main parameter you need to pass is the separator. The separator can be a hyphen, comma or a space. Split (”): when you pass an empty string into the split method, it will then split every character in an array.
Split variable from last space in a string var lname = fullname. substring(fullname. lastIndexOf(” “) + 1, fullname. length);
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
You should correct your jquery first selector. Correct way of selecting your input box by specifying your id selector. Because selector case sensitive. $('#thVal').
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(/(.+)(\..+)/);
var str = "[email protected]";
var test = str.split(".");
var extension = test[test.length - 1];
var filename = str.replace("."+extension,"");
Updated Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With