Reputation: 21
I'm embarked on a JavaScript journey, and have the following code which I really need to understand in details. Especially the line where it says if (str.slice(i, i + 2) === " ")
var str = prompt("Enter some text");
var numChars = str.length;
for (var i = 0; i < numChars; i++) {
if (str.slice(i, i + 2) === " ") {
alert("No double spaces!");
break;
}
}
Upvotes: 2
Views: 560
Reputation: 2452
str.slice(i, i + 2)
inside a for
loop will parse the string str
taking two consecutive characters at a time with indices i
and i+1
where i
will have all values from 0
to length
of str
according to the for
loop.
Note : In your code snippet by this if(str.slice(i, i + 2) === " ")
you are comparing two characters with single character which is white space. So it can never be true.
Have a look at a better example for more clear understanding.
var str1 = "Single space";
var str2 = "Double space";
var numChars1 = str1.length;
var numChars2 = str2.length;
// Check is str1 has double spaces
for (var i = 0; i < numChars1; i++) {
if (str1.slice(i, i + 2) === " ") {
console.log("Double spaces found in str1");
break;
}
}
// Check is str2 has double spaces
for (var i = 0; i < numChars1; i++) {
if (str2.slice(i, i + 2) === " ") {
console.log("Double spaces found in str2");
break;
}
}
Learn and find more example about slice on w3schools
Upvotes: 0
Reputation: 386560
You are comparing with a single space.
if (str.slice(i, i + 2) === " ") {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^ single space
The comparison is only true
in one case, at the end of the string with a single space. All other comparisons evaluates to false
, because a string with the length of two is never equal to a string with a single character.
Upvotes: 1
Reputation: 6780
It's saying that, for each letter i
in the entered text, to the letter i + 2
, if they are equal to " "
, then they are two spaces.
In other words, it is checking each of the two letter combinations in the text to see if they match two spaces
For example:
"En", "nt", "te", "er", "r ", " s", "so", "om"
etc...
So, slice is 'slicing' letters in the range specified in the parameters: str.slice(beginIndex[, endIndex])
Edit: Didn't see the prompt() call, so updated accordingly.
Perhaps try this in order to get a better idea of what's happening:
var str = prompt("Enter some text");
var numChars = str.length;
for (var i = 0; i < numChars; i++) {
if (str.slice(i, i + 2) === " ") {
alert("No double spaces!");
break;
} else {
document.write(str.slice(i, i + 2) + "<br>")
}
}
Upvotes: 0