ABaut
ABaut

Reputation: 145

Splitting names and rootnames using javascript

I am creating a simple program that prompts the user to type in a filename with its extension and my program will separate the filename and the rootname. Essentially, my goal looks like this below:

userinput=Jack.html
filename=Jack
rootname=html

I was able to separate it using the split function and accessing the separately but my problem is when the user input has multiple periods for example like this

userinput= Jack.1.2.html
filename=Jack.1.2
rootname=html

How do I go about separating the user input when it has multiple periods. Here is my code. I want to work for multiple periods as well:

var userinput, splitinput; 
var rootname, filename;

userinput= prompt('Enter filename:') //
splitinput=userinput.split('.')
filename= splitinput[0]
rootname=splitinput[1]+ userinput[2]
console.log(filename)
console.log(rootname)

Upvotes: 1

Views: 49

Answers (3)

Jared Farrish
Jared Farrish

Reputation: 49208

Use Array.slice() with a negative argument to trim the last part of the array off (e.g., html), then re-join:

var userinput = prompt('Enter filename:'),
    filename = userinput.split('.').slice(0, -1).join('.') || userinput;

alert('Filename: ' + filename);

http://jsfiddle.net/u3nb2ctL/

Upvotes: 1

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

You can accomplish this using pop() and join(). Effectively we split the string by periods, then pop off the last one, and then we get the two sections of the string (rootname and filename).

Here is a live demo:

var userinput = prompt('Enter filename:');
var splitinput = userinput.split('.');
var rootname = splitinput.pop();
var filename = splitinput.join(".");

document.getElementById("output1").textContent = filename;
document.getElementById("output2").textContent = rootname;
<div>Filename: <span id="output1"></span></div>
<div>Rootname: <span id="output2"></span></div>

Upvotes: 1

Joseph Tinoco
Joseph Tinoco

Reputation: 2225

Split it by the position of the last period, like this:

    var userinput; 
    var rootname, filename;
    
    userinput= prompt('Enter filename:') //
    filename= userinput.substring(0,userinput.lastIndexOf('.'))
    rootname=userinput.substring(userinput.lastIndexOf('.')+1)
    console.log(filename)
    console.log(rootname)

Upvotes: 1

Related Questions