Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - splitting a string and passing all values to a function

Tags:

javascript

The string is

var str = "Beautiful Day";

I am splitting the str using white space as the separator

var substr = str.split(" ");

The above should return 2 words and so the length of the string should be 2

var strLength = substr.length;

Now, I want to pass both the words as separate parameters of a function such that:

myFunction(word1, word2)

But I don't want to use

substr[0]
substr[1]
like image 314
techlead Avatar asked Sep 22 '26 03:09

techlead


1 Answers

Since split returns an array, the apply method is perfect for you:

var str = 'It is a beautiful day';
alertEmAll.apply(null, str.split(' '));


function alertEmAll(){
    for(var i = 0; i < arguments.length; i++)
        alert(arguments[i]);
}

Edit

Since you have a variable number of arguments, you may also want to use the arguments array-like object. The above code will alert all the words in your input string, one after the other.

like image 107
Paul Avatar answered Sep 23 '26 19:09

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!