Nigel
Nigel

Reputation: 3

JavaScript : Split string using function and returning it

I don't know what I'm doing wrong here. Tried several thinks but the function doesn't work/return properly (The html code is okay)

var divResult = document.getElementById("divResult");
var naam;

function splitsen(naam){
    var res = naam.split(" ");
    document.write(res[0]);
    var voornaam = res[0];
    var achternaam = res[1];
    var tnaam = [voornaam, achternaam];
return tnaam;
}

naam = parseInt(prompt("Geef je voornaam en achternaam in gescheiden met een spatie"));

var voornaam = splitsen(naam)[0];
var achternaam = splitsen(naam)[1];
divResult.innerHTML = "oefening 8";
divResult.innerHTML += "Voornaam: " + voornaam;
divResult.innerHTML += "Achternaam" + achternaam;
divResult.innerHTML += "Email: " + voornaam + "." + achternaam + "@student.arteveldehs.be";

Upvotes: 0

Views: 46

Answers (2)

Aiman Al-Eryani
Aiman Al-Eryani

Reputation: 709

I could spot 2 problems in your code:

1-The parameter name to your function is the same name as that of a global variable. It is probable that any references to 'naam' in your function use the global variable instead of what you pass. Regardless, don't do that.

2-parseInt will take a string and extract an integer out of it and returns a number. number types doesn't have the split() method and you probably wanted a string containing the name.

Upvotes: 0

Max
Max

Reputation: 2806

parseInt('My Name'); returns NaN.

Remove the parseInt(), and just keep it as:

var naam = prompt('Input your name seperated by a space.');

Upvotes: 1

Related Questions