Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in jquery

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.

like image 480
Sara Avatar asked Nov 08 '14 04:11

Sara


People also ask

What is the use of split in JQuery?

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.

How split a string with space in JQuery?

Split variable from last space in a string var lname = fullname. substring(fullname. lastIndexOf(” “) + 1, fullname. length);

What is split () function in string?

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.

Why split is not working in JQuery?

You should correct your jquery first selector. Correct way of selecting your input box by specifying your id selector. Because selector case sensitive. $('#thVal').


2 Answers

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(/(.+)(\..+)/);
like image 83
Nathan Avatar answered Oct 19 '22 06:10

Nathan


var str = "[email protected]";
var test = str.split(".");

var extension = test[test.length - 1];
var filename = str.replace("."+extension,"");

Updated Demo

like image 42
Nima Derakhshanjan Avatar answered Oct 19 '22 04:10

Nima Derakhshanjan