Repository navigation
JavaScript Basics
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.
The length property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length; // 26
- indexOf()
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"); // 7
- lastIndexOf()
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"); // 21
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
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"); // 7
Did You Notice?
The two methods, indexOf() and search(), are equal.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.
You will learn more about powerful search values in the chapter about regular expressions.
There are 3 methods for extracting a part of a string:
- slice(start, end)
- substring(start, end)
- substr(start, length)
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position, inclusive), and the ending index (position, exclusive).
This example slices out a portion of a string from position 7 to position 13:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13); // "Banana"
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:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6); // "Banana"
If you omit the second parameter, the method will slice out the rest of the string:
var res = str.slice(7); // "Banana, Kiwi" var res = str.slice(-4); // "Kiwi"
Negative positions do not work in Internet Explorer 8 and earlier.
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13); // "Banana"
If you omit the second parameter, substring() will slice out the rest of the string.
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6); // "Banana"
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, 3); // "Kiw"
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
var str = "Apple, Banana, Kiwi";
var res = str.substr(12); // "a, Kiwi"
The replace() method replaces a specified value with another value in a string. It does not change the string it is called on. It returns a new string.
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools"); // "Please visit W3Schools!"
The replace() method can also take a regular expression as the search value.
By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a g flag (for global match):
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/, "W3Schools"); // "Please visit W3Schools and Microsoft!"
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools"); // "Please visit W3Schools and W3Schools!"
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // "HELLO WORLD!"
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // "hello world!"
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ", text2); // "Hello World!"
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!");
There are 2 safe methods for extracting string characters:
- charAt(position)
- charCodeAt(position)
The charAt() method returns the character at a specified index (position) in a string:
var str = "HELLO WORLD";
str.charAt(0); // returns "H"
The charCodeAt() method returns the unicode of the character at a specified index in a string:
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
You might have seen code like this, accessing a string as an array:
var str = "HELLO WORLD";
str[0]; // returns H
This is unsafe and unpredictable:
- It does not work in all browsers (not in IE5, IE6, IE7)
- It makes strings look like arrays (but they are not)
- str[0] = "H" does not give an error (but does not work)
If you want to read a string as an array, convert it to an array first.
A string can be converted to an array with the split() method:
var txt = "a,b,c,d,e"; // String
var arr = txt.split(","); // Split on commas, arr = ['a','b','c','d','e'].
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0]:
var txt = "a,b,c,d,e";
var arr = txt.split();
console.log(arr[0]); // "a,b,c,d,e"
If the separator is "", the returned array will be an array of single characters:
var txt = "a,b,c,d,e";
var arr = txt.split(""); // arr = ['a',',','b',',','c',',','d',',','e']
var txt = "Hello"; // String
txt.split(""); // Split in characters, ['H','e','l','l','o']
Thanks for W3School.