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”)
There are 3 methods in JavaScript to get a substring:
substring, substr and slice.
Returns the part of the string between start and end (not including end). This is almost the same as slice, but it allows start to be greater than end (in this case it simply swaps start and end values).
str.substring(start [, end])
let str = “stringify”;
alert( str.slice(0, 5) ); //returns
‘strin’, the substring from 0 to 5 (not including 5)
let str = “stringify”;
alert( str.slice(0, 1) ) // returns
; // ‘s’, from 0 to 1, but not including 1, so only character at 0
let str = “stringify”;
alert( str.slice(2) ); //
‘ringify’, from the 2nd position till the end
If there is no second argument, then slice goes till the end of the string:
let str = “stringify”;
alert( str.slice(2, 6) );
// “ring”
Returns the part of the string from start, with the given length
str.substr(start [, length])