JavaScript String Methods Flashcards
String methods help you to work with strings.
String Methods and Properties
Primitive values, like “John Doe”, cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String Length
The length property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;
code to display txt.length in “demo”:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = txt.length;
Finding a String in a String The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); Show code to display location:
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third …
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate");
Both indexOf(), and lastIndexOf() return -1 if the text is not found. Both methods accept a second parameter as the starting position for the search:
The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string.
var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate", 15);
The lastIndexOf() method accepts a second parameter as the starting position for the search.
Remember that the lastIndexOf() method searches backwards, so position 15 means start the search at position 15, and search to the beginning.
Position 15 is position 15 from the beginning.
7
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); document.getElementById("demo").innerHTML = pos;
displays:
7
next
var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate"); document.getElementById("demo").innerHTML = pos;
displays: 21
next
Both methods accept a second parameter as the starting position for the search: var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate",15); document.getElementById("demo").innerHTML = pos;
displays: 21
Searching for a String in a String The search() method searches a string for a specified value and returns the position of the match:
var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); The search() method returns the position of the first occurrence of a specified text in a string:
The search() method returns the position of the first occurrence of a specified text in a string:
7
var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); document.getElementById("demo").innerHTML = pos;
var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); document.getElementById("demo").innerHTML = pos;
Did You Notice?
The two methods, indexOf() and search(), are equal?
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
The search() method cannot take a second start position argument. The indexOf() method cannot take powerful search values (regular expressions). You will learn more about regular expressions in a later chapter.
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
The slice() Method
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
The substring() Method
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
The substr() Method
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
The slice() Method
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Extract “Banana from” Apple, Banana, Kiwi”;
Name the variables str and res.
Remember: JavaScript counts positions from zero. First position is 0.
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
“Apple, Banana, Kiwi”: What does code look like for these parameters?
If you omit the second parameter, the method will slice out the rest of the string:
Code that displays: Banana, Kiwi
Negative positions do not work in Internet Explorer 8 and earlier.
var str = "Apple, Banana, Kiwi"; var res = str.slice(7,13); document.getElementById("demo").innerHTML = res;
var str = "Apple, Banana, Kiwi"; var res = str.slice(-12,-6); document.getElementById("demo").innerHTML = res;
var str = "Apple, Banana, Kiwi"; var res = str.slice(7); document.getElementById("demo").innerHTML = res;
The substring() Method substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
“Apple, Banana, Kiwi”
Display Banana:
If you omit the second parameter, substring() will slice out the rest of the string.
var str = "Apple, Banana, Kiwi"; var res = str.substring(7,13); document.getElementById("demo").innerHTML = res;
The substr() Method substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
“Apple, Banana, Kiwi”
Display Banana:
If you omit the second parameter, substr() will slice out the rest of the string.
var str = “Apple, Banana, Kiwi”;
var res = str.substr(7);
Banana, Kiwi
If the first parameter is negative, the position counts from the end of the string. var str = "Apple, Banana, Kiwi"; var res = str.substr(-4); The result of res will be: Kiwi
var str = "Apple, Banana, Kiwi"; var res = str.substr(7,6); document.getElementById("demo").innerHTML = res;
Replacing String Content The replace() method replaces a specified value with another value in a string:
var str = "Please visit Microsoft!"; var txt = str.replace("Microsoft", "W3Schools");
The replace() method does not change the string it is called on. It returns a new string.
By default, the replace() method replaces only the first match.
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work.
To replace case insensitive, use a regular expression with an /i flag (insensitive): var str = document.getElementById("demo").innerHTML; var txt = str.replace(/MICROSOFT/i,"W3Schools");
Note that regular expressions are written without quotes.
To replace all matches, use a regular expression with a /g flag (global match): var str = document.getElementById("demo").innerHTML; var txt = str.replace(/Microsoft/g,"W3Schools");
button onclick=”myFunction()”>Try it/button>
p id=”demo”>Please visit Microsoft!/p>
function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace("Microsoft","W3Schools"); document.getElementById("demo").innerHTML = txt; }
Converting to Upper and Lower Case A string is converted to upper case with toUpperCase(): var text1 = "Hello World!"; // String var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase(): var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
function myFunction() { var text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.toUpperCase(); }
next
function myFunction() { var text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.toLowerCase(); }
The concat() Method concat() joins two or more strings:
Example var text1 = "Hello"; var text2 = "World"; var text3 = text1.concat(" ", text2);
The concat() method can be used instead of the plus operator. These two lines do the same: var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ", "World!");
All string methods return a new string. They don’t modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
var text1 = "Hello"; var text2 = "World!"; var text3 = text1.concat(" ",text2); document.getElementById("demo").innerHTML = text3;
displays:
The concat() method joins two or more strings:
Hello World!
String.trim() The trim() method removes whitespace from both sides of a string:
Example
var str = “ Hello World! “;
alert(str.trim());
Note: The trim() method is not supported in Internet Explorer 8 and earlier versions.
If you need to support IE 8, you can use replace() with a regular expression instead:
var str = “ Hello World! “;
alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ‘’));
You can also use the replace solution above to add a trim function to the JavaScript String.prototype: if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; var str = " Hello World! "; alert(str.trim());
function myFunction() { var str = " Hello World! "; alert(str.trim()); }
Extracting String Characters
There are 3 methods for extracting string characters:
charAt(position)
charCodeAt(position)
Property access [ ]
The charAt() method returns the character at a specified index (position) in a string.
The charCodeAt() method returns the unicode of the character at a specified index in a string: The method returns a UTF-16 code (an integer between 0 and 65535).
Property Access ECMAScript 5 (2009) allows property access [ ] on strings.
The charAt() method returns the character at a specified index (position) in a string: var str = "HELLO WORLD"; str.charAt(0); // returns H
var str = "HELLO WORLD"; document.getElementById("demo").innerHTML = str.charAt(0);
The charCodeAt() Method The charCodeAt() method returns the unicode of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535). var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
var str = "HELLO WORLD"; document.getElementById("demo").innerHTML = str.charCodeAt(0);
returns:
The charCodeAt() method returns the unicode of the character at a given position in a string:
72
Property Access ECMAScript 5 (2009) allows property access [ ] on strings: var str = "HELLO WORLD"; str[0]; // returns H
Property access might be a little unpredictable:
It does not work in Internet Explorer 7 or earlier It makes strings look like arrays (but they are not) If no character is found, [ ] returns undefined, while charAt() returns an empty string. It is read only. str[0] = "A" gives no error (but does not work!) Example: var str = "HELLO WORLD"; str[0] = "A"; // Gives no error, but does not work str[0]; // returns H
If you want to work with a string as an array, you can convert it to an array.
var str = "HELLO WORLD"; document.getElementById("demo").innerHTML = str[0];
returns:
ECMAScript 5 allows property acces on strings:
H
next
var str = "HELLO WORLD"; str[0] = "A"; // Does not work document.getElementById("demo").innerHTML = str[0];
returns:
ECMAScript 5 allows property acces on strings. but read only:
H