javascriptfor-loopconcatenationindexoflastindexof

For loop inside a string to concatenate the characters in a variable (without RegExp)- Javascript


I am trying to loop through a string variable and save every char inside an other variable. My code looks like this:

    var str = "hello world";
    var res = "";

    for (var i = str.indexOf("hello"); i <= str.lastIndexOf("hello"); i++) {
        res = res.concat(str.charAt(i));    
    }

    console.log("The result is: " + res);

It looks really logical for me, but it prints only the 1st letter. I expected it to say hello. What's the problem? Can't be done without a Regexp?


Solution

  • You need the length and the start postion for checking the index.

    var str = "bla bla hello world",
        res = "",
        i,
        l = "hello".length,
        p = str.indexOf("hello");
    
    for (i = p; i < p + l; i++) {
        res += str[i];
    }
    
    console.log("The result is: " + res);