Two word prayer stored in var Javascript

0

If I keep a sentence that will always consist of one or two words in a variable var , how do I save the first word in one variable and the second in another, in the event that the sentence be of two words, and to know that (if the sentence in var is one or two words) how can I do an if?.

    
asked by isalvinator 11.12.2017 в 04:05
source

1 answer

1

Use the function split() of javascript, if the sentence is separated by spaces add (" ") if it is a different character for example comas var cad="hola,adios" usa .split(",")

  

Documentation String.prototype.split ()

var str = "hola adios";
var res = str.split(" "); 
var cont=0;
res.forEach(function(element) {
    cont++;
});
if(cont==2){
    var cad1=res[0];
    var cad2=res[1];
}else if(cont==1){
    var cad1=res[0];
}else{
    //si es diferente a 1 o 2
}
    
answered by 11.12.2017 / 04:58
source