Reference
Getting the Length of a String
Finding a String Inside Another String
Searching for a Pattern Inside a String
Extracting a Substring from a String
Extracting a Fixed Number of Characters from a String
Converting a String to Uppercase or Lowercase
Accessing Individual Characters from a String
Splitting a String into an Array
How to split a string by the last dot in JavaScript?
How to split a string into substrings of N characters in JavaScript?
How to add a string to the beginning and end of a string in JavaScript?
How to split string and remove surrounding spaces in JavaScript?
How to insert string at a specific index of another string in JavaScript?
How to split a string by comma or space in JavaScript?
How to split a string by multiple spaces in JavaScript?
How to split a string without removing delimiter in JavaScript?
Getting the Length of a String
The length property returns the length of the string, which is the number of characters contained in the string. This includes the number of special characters as well, such as \t or \n.
var str1 = "This is a paragraph of text.";
document.write(str1.length); // Prints 28
var str2 = "This is a \n paragraph of text.";
document.write(str2.length); // Prints 30, because \n is only one character
Note: Since length is a property, not a function, so don't use parentheses after it like str.length(). Instead just write str.length, otherwise it will produce an error.
Finding a String Inside Another String
You can use the indexOf() method to find a substring or string within another string. This method returns the index or position of the first occurrence of a specified string within a string.
var str = "If the facts don't fit the theory, change the facts.";
var pos = str.indexOf("facts");
alert(pos); // 0utputs: 7
Similarly, you can use the lastIndexOf() method to get the index or position of the last occurrence of the specified string within a string, like this:
var str = "If the facts don't fit the theory, change the facts.";
var pos = str.lastIndexOf("facts");
alert(pos); // 0utputs: 46
Both the indexOf(), and the lastIndexOf() methods return -1 if the substring is not found. Both methods also accept an optional integer parameter which specifies the position within the string at which to start the search. Here's an example:
var str = "If the facts don't fit the theory, change the facts.";
// Searching forwards
var pos1 = str.indexOf("facts", 20);
alert(pos1); // 0utputs: 46
// Searching backwards
var pos2 = str.lastIndexOf("facts", 20);
alert(pos2); // 0utputs: 7
Note: Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called myStr is myStr.length - 1.
Searching for a Pattern Inside a String
You can use the search() method to search a particular piece of text or pattern inside a string.
Like indexOf() method the search() method also returns the index of the first match, and returns -1 if no matches were found, but unlike indexOf() method this method can also take a regular expression as its argument to provide advanced search capabilities.
var str = "Color red looks brighter than color blue.";
// Case sensitive search
var pos1 = str.search("color");
alert(pos1); // 0utputs: 30
// Case insensitive search using regexp
var pos2 = str.search(/color/i);
alert(pos2); // 0utputs: 0
Note: The search() method does not support global searches; it ignores the g flag or modifier (i.e. /pattern/g) of its regular expression argument.
You will learn more about regular expressions in the upcoming chapters.
Extracting a Substring from a String
You can use the slice() method to extract a part or substring from a string.
This method takes 2 parameters: start index (index at which to begin extraction), and an optional end index (index before which to end extraction), like str.slice(startIndex, endIndex).
The following example slices out a portion of a string from position 4 to position 15:
var str = "The quick brown fox jumps over the lazy dog.";
var subStr = str.slice(4, 15);
document.write(subStr); // Prints: quick brown
You can also specify negative values. The negative value is treated as strLength + startIndex, where strLength is the length of the string (i.e. str.length), for example, if startIndex is -5 it is treated as strLength - 5. If startIndex is greater than or equal to the length of the string, slice() method returns an empty string. Also, if optional endIndex is not specified or omitted, the slice() method extracts to the end of the string.
var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.slice(-28, -19)); // Prints: fox jumps
document.write(str.slice(31)); // Prints: the lazy dog.
You can also use the substring() method to extract a section of the given string based on start and end indexes, like str.substring(startIndex, endIndex). The substring() method is very similar to the slice() method, except few differences:
If either argument is less than 0 or is NaN, it is treated as 0.
If either argument is greater than str.length, it is treated as if it were str.length.
If startIndex is greater than endIndex, then substring() will swap those two arguments; for example, str.substring(5, 0) == str.substring(0, 5).
The following example will show you how this method actuallty works:
var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.substring(4, 15)); // Prints: quick brown
document.write(str.substring(9, 0)); // Prints: The quick
document.write(str.substring(-28, -19)); // Prints nothing
document.write(str.substring(31)); // Prints: the lazy dog.
Extracting a Fixed Number of Characters from a String
JavaScript also provide the substr() method which is similar to slice() with a subtle difference, the second parameter specifies the number of characters to extract instead of ending index, like str.substr(startIndex, length). If length is 0 or a negative number, an empty string is returned. The following example demonstrates how it works:
var str = "The quick brown fox jumps over the lazy dog.";
document.write(str.substr(4, 15)); // Prints: quick brown fox
document.write(str.substr(-28, -19)); // Prints nothing
document.write(str.substr(-28, 9)); // Prints: fox jumps
document.write(str.substr(31)); // Prints: the lazy dog.
Replacing the Contents of a String
You can use the replace() method to replace part of a string with another string. This method takes two parameters a regular expression to match or substring to be replaced and a replacement string, like str.replace(regexp|substr, newSubstr).
This replace() method returns a new string, it doesn't affect the original string that will remain unchanged. The following example will show you how it works:
var str = "Color red looks brighter than color blue.";
var result = str.replace("color", "paint");
alert(result); // 0utputs: Color red looks brighter than paint blue.
By default, the replace() method replaces only the first match, and it is case-sensitive. To replace the substring within a string in a case-insensitive manner you can use a regular expression (regexp) with an i modifier, as shown in the example below:
var str = "Color red looks brighter than color blue.";
var result = str.replace(/color/i, "paint");
alert(result); // 0utputs: paint red looks brighter than color blue.
Similarly, to replace all the occurrences of a substring within a string in a case-insensitive manner you can use the g modifier along with the i modifier, like this:
var str = "Color red looks brighter than color blue.";
var result = str.replace(/color/ig, "paint");
alert(result); // 0utputs: paint red looks brighter than paint blue.
Converting a String to Uppercase or Lowercase
You can use the toUpperCase() method to convert a string to uppercase, like this:
var str = "Hello World!";
var result = str.toUpperCase();
document.write(result); // Prints: HELLO WORLD!
Similarly, you can use the toLowerCase() to convert a string to lowercase, like this:
var str = "Hello World!";
var result = str.toLowerCase();
document.write(result); // Prints: hello world!
Concatenating Two or More Strings
You can concatenate or combine two or more strings using the + and += assignment operators.
var hello = "Hello";
var world = "World";
var greet = hello + " " + world;
document.write(greet); // Prints: Hello World
var wish = "Happy";
wish += " New Year";
document.write(wish); // Prints: Happy New Year
JavaScript also provides concat() method to combine strings, but it is not recommended.
Accessing Individual Characters from a String
You can use the charAt() method to access individual character from a string, like str.charAt(index). The index specified should be an integer between 0 and str.length - 1. If no index is provided the first character in the string is returned, since the default is 0.
var str = "Hello World!";
document.write(str.charAt()); // Prints: H
document.write(str.charAt(6)); // Prints: W
document.write(str.charAt(30)); // Prints nothing
document.write(str.charAt(str.length - 1)); // Prints: !
There is even better way to do this. Since ECMAScript 5, strings can be treated like read-only arrays, and you can access individual characters from a string using square brackets ([]) instead of the charAt() method, as demonstrated in the following example:
var str = "Hello World!";
document.write(str[0]); // Prints: H
document.write(str[6]); // Prints: W
document.write(str[str.length - 1]); // Prints: !
document.write(str[30]); // Prints: undefined
Note: The only difference between accessing the character from a string using the charAt() and square bracket ([]) is that if no character is found, [] returns undefined, whereas the charAt() method returns an empty string.
Splitting a String into an Array
The split() method can be used to splits a string into an array of strings, using the syntax str.split(separator, limit). The seperator argument specifies the string at which each split should occur, whereas the limit arguments specifies the maximum length of the array.
If separator argument is omitted or not found in the specified string, the entire string is assigned to the first element of the array. The following example shows how it works:
var fruitsStr = "Apple, Banana, Mango, Orange, Papaya";
var fruitsArr = fruitsStr.split(", ");
document.write(fruitsArr[0]); // Prints: Apple
document.write(fruitsArr[2]); // Prints: Mango
document.write(fruitsArr[fruitsArr.length - 1]); // Prints: Papaya
*// Loop through all the elements of the fruits array *
for(var i in fruitsArr) {
document.write("<p>" + fruitsArr[i] + "</p>");
}
To split a string into an array of characters, specify an empty string ("") as a separator.
var str = "INTERSTELLAR";
var strArr = str.split("");
document.write(strArr[0]); // Prints: I
document.write(strArr[1]); // Prints: N
document.write(strArr[strArr.length - 1]); // Prints: R
// Loop through all the elements of the characters array and print them
for(var i in strArr) {
document.write("<br>" + strArr[i]);
}
1** How to split a string by the last dot in JavaScript?**
click here
using arr.pop() and arr.join()
How to split a string into substrings of N characters in JavaScript using match?click here
How to add a string to the beginning and end of a string in JavaScript?click here
How to split string and remove surrounding spaces in JavaScript using split and array map?click here
How to split a string by multiple spaces in JavaScript?
click here
How to split a string without removing delimiter in JavaScript?
click here
How to url validation using lastindex,slice in JavaScript?
-
How to url validation using includes in JavaScript?
-
scenario where the string doesn't contain a dot
Top comments (0)