Oliver Jones
Oliver Jones

Reputation: 1450

JavaScript - Split A String

I have a variable that holds the value 'website.html'.

How can I split that variable so it only gives me the 'website'?

Thanks

Upvotes: 19

Views: 76518

Answers (3)

paulslater19
paulslater19

Reputation: 5917

var a = "website.html";
var name = a.split(".")[0];

If the file name has a dot in the name, you could try...

var a = "website.old.html";
var nameSplit = a.split(".");
nameSplit.pop();    
var name = nameSplit.join(".");

But if the file name is something like my.old.file.tar.gz, then it will think my.old.file.tar is the file name

Upvotes: 42

JonnyReeves
JonnyReeves

Reputation: 6209

Another way of doing things using some String manipulation.

var myString = "website.html";
var dotPosition = myString.indexOf(".");
var theBitBeforeTheDot = myString.substring(0, dotPosition);

Upvotes: 3

K2xL
K2xL

Reputation: 10330

String[] splitString = "website.html".split(".");
String prefix = splitString[0];

*Edit, I could've sworn you put Java not javascript

var splitString = "website.html".split(".");
var prefix = splitString[0];

Upvotes: 4

Related Questions