I have this line

var str = "example1 example2 example3 .... exampleN"; 

Well, you understand the meaning. I do not know how many words in the string str. I need to choose only the first (in the sense of the first space). To after funkts. I got "example1".

2 answers 2

Why not use the split () method? Although the cycle is also normal, it immediately finds the first necessary element and finishes the work, just a bit too much code, it can be easier

 var str = "example1 example2 example3 .... exampleN"; str = str.split(' '); //отделит все что с пробелом console.log(str[0]); 
     <script type="text/javascript"> var str = new Array('ex1', 'ex2', 'ex3'); document.write(str[0]); </script> 
    • You initially know that 3 values, I have already found a solution, wrote the function var str = "example1 example2 example4 example45 and so"; var n = str.length; var j; for (i = 0; i <n; i ++) {if (str [i] == "") {j = i; break; }} alert (str.substr (0, j)); - Elivin87