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?
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?
str.lastIndexOf("hello")
does not do what you think it does. It does not tell you where o
is....
– epascarello
Commented
Aug 29, 2017 at 20:27
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);
Replace str.lastIndexOf("hello")
with pattern.length
:
var str = "hello world";
var pattern = "hello";
var res = "";
var index = str.indexOf(pattern);
for (var i = index; i <= index + pattern.length; i++) {
res = res.concat(str.charAt(i));
}
console.log("The result is: " + res);
From documentation:
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
It's not the index of the last character.
For loop inside a string to concatenate the characters in a variable (without RegExp)
var theString = "This is my string";
var theArray = [];
var theResultString = "";
doIt(theString);
doitagain(theString)
function doIt(iningString)
{
//concatenate into an array object
for(var i = 0; i < iningString.length; i++)
{
theArray.push(iningString.substring(i, i+1))
}
console.log(theArray);
}
function doitagain(iningString)
{
//concatenating into a string object
for(var i = 0; i < iningString.length; i++)
{
theResultString += iningString.substring(i, i+1);
}
console.log(theResultString);
}