Strings Flashcards
alert( My\n
.length ); // returns and why?
3
Note that \n is a single “special” character, so the length is indeed 3.
let str = Hello
;
alert( str[-2] ); //
undefined
let str = Hello
;
alert( str[0] ); // returns?
H
let str = Hello
;
// the first character
alert( CODE HERE ); // H
alert( CODE HERE ); // H
str[0]
str.at(0)
let str = Hello
;
// the last character
alert( ); // o
alert( );
str[str.length - 1]
str.at(-1)
how to iterate through “hello”
use for..of
for (let char of “Hello”) {
alert(char);
}
let str = ‘Hi’;
str[0] = ‘h’; // error
alert( str[0] ); // doesn’t work
how to fix
str = ‘h’ + str[1]; // replace the string
change to upper or lower case
.toUpperCase()
.toLowerCase()
It looks for the substr in str, starting from the given position pos, and returns the position where the match was found or -1 if nothing can be found.
str.indexOf()
let str = ‘Widget with id’;
alert( str.indexOf(‘widget’) ); //
-1, not found, the search is case-sensitive
let str = ‘Widget with id’;
alert( str.indexOf(‘id’, 2) ) //
12
alert(‘interface’ ); //
change first i to lower case
‘Interface’[0].toLowerCase()
let str = “Widget with id”;
if (str.indexOf(“Widget”)) {
alert(“We found it”); // doesn’t work!
}
how to fix?
let str = “Widget with id”;
if (str.indexOf(“Widget”) != -1) {
alert(“We found it”); // works now!
}
The alert in the example above doesn’t show because str.indexOf(“Widget”) returns 0 (meaning that it found the match at the starting position). Right, but if considers 0 to be false.
So, we should actually check for -1, like this:
The more modern method ________returns true/false depending on whether str contains substr within.
str.includes(substr, pos)
alert( “Widget” );
// true, “Widget” starts with “Wid”
alert( “Widget” );
// true, “Widget” ends with “get”
.startsWith(“Wid”)
.endsWith(“get”)