19

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

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

Thanks

1
  • 6
    @Jack This page was the first hit when I Googled "javascript split string dot". Saying "Google it" helps no one. Commented Jan 27, 2018 at 4:24

3 Answers 3

42
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

Sign up to request clarification or add additional context in comments.

2 Comments

This does not work, if the filename has a dot in its name like: my.super.website.html.
var nameSplit = a.split("."); nameSplit.pop(); var name = nameSplit.join("."); Make nameSplit.join(".") instead of name.join(".") , It will work.
4
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];

Comments

3

Another way of doing things using some String manipulation.

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

4 Comments

+1 This requires more code, but don't requires aditional comments to understand.
I remember learning basic string manipulation before the quicker 'Array.split' method clicked with me (:
It's worth noting that some older browsers do not support .indexOf()
@JonnyReeves Whoops, yes, you're right - I was thinking about [].indexOf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.