JavaScript Strings

About JavaScript Strings

In JavaScript, strings represent sequences of characters enclosed within single or double quotation marks.

Strings are used to store text, words, sentences, and other textual information.

They are immutable. Once a string is created, it cannot be modified directly. Rather, string methods return new strings.

String Declaration

Strings can be declared by placing the specified text between single quotes (' ') or double quotes (" ") as demonstrated in the following examples:

Output of the above example
Hello World!
Welcome to xfactorschool.com
                                                        
Explanation of the code
  • let message = 'Hello World!';: This line declares a variable named 'message' and assigns the text Hello World! between single quotes (' and '). Thus a string is created.
  • let greetings = "Welcome to xfactorschool.com"; : This line declares a variable named 'greetings' and assigns the text Welcome to xfactorschool.com between double quotes (" and "). Thus another string is created.
  • console.log(message);: In the line, 'console.log()' method prints the string value of 'message' variable in the web console.
  • console.log(greetings);: In the line, 'console.log()' method prints the string value of 'greetings' variable in the web console.

JS String Constructor

The JavaScript 'String()' constructor can be used to convert other data types to strings as demonstrated in the following examples:

JS String length Property

The JavaScript string 'length' property returns the length of the string as demonstrated in the following example:

The length of a string includes the white spaces in the string.

Methods of JavaScript String

  • charAt(index) : This method returns the character at the specified index of the string.

    In the above example, charAt() method returns the char "H" as it is at 0 index of the string.


  • charCodeAt(index) : This method returns the Unicode of the character at the specified index of the string.

    In the above example, charCodeAt() method returns 72 which is the Unicode of "H" ("H" is the char at 0 index of the string).


  • concat(string2, ..., stringN)) : This method concatenates (joins) two or more strings into a single string.

    In the above example, concat() method joins strings "JavaScript ", "is fun at ", and "XFactorSchool." and returns a new string "JavaScript is fun at XFactorSchool".


  • includes(substring) : This method checks if the string contains the specified substring and returns a Boolean value.

    In the above example, the includes() method checks if "fun" exists in the string "JavaScript is fun." and returns true as the search string is present in the string.


  • indexOf(searchString, startingPosition) : The indexOf() method returns the index of the first occurrence of the specified search value if found. It returns -1 if not found. The second parameter 'startingPosition' specifies the position (index) within the string from where the search will start. It is a optional parameter.

    In the above example, str.indexOf("fun") returns the index of the first occurrence of the substring "fun". Whereas str.indexOf("fun", 15) starts searching from the index 15 of the string and returns the index of the first occurrence of the substring "fun".


  • lastIndexOf(searchString, lastPosition) : The lastIndexOf() method returns the index of the last occurrence of the specified search value if found. It returns -1 if not found. The second parameter 'lastPosition' specifies the position (index) within the string upto which the search will continue. It is a optional parameter.

    In the above example, str.lastIndexOf("fun") returns the index of the last occurrence of the substring "fun" in the string. Whereas str.lastIndexOf("fun", 20) returns the index of the last occurrence of the substring "fun" before or at index position 20 of the string.


  • search(regex) : This search() method executes a search for a match between a regular expression and the current string and returns the index of the first match in the string. It returns -1, if not found.

    In the above example, str.search(/is/) returns the index of the first match of the string "is" in the string using regular expression.

    In the second example, str.search(regex) returns the index of the first match of the string "Script" in the string using regular expression stored in variable 'regex'.


  • match(regex) : This match() method retrieves the result of matching this string against a regular expression.

    In the above example, str.match(regex) returns the phone number 121-253-2254 based on regular expression (/\d{3}-\d{3}-\d{4}/).


  • slice(startIndex, endIndex) : This slice() method extracts a section of a string and returns it as a new string. The slice starts at the index specified in the first argument and ends before the index specified in the second argument (excluding the char at the last index).

    In the above example, str.slice(0, 10) extracts the substring from index 0 to index 10, resulting in "JavaScript". (Please note that the char at index 10 is excluded).


  • split(separator, limit) : The split() method splits a string into an array of substrings based on the specified separator.

    In the above example, str.split(", ") returns an array of substring (['apple', 'banana', 'orange']) based on the separator ", ".


  • substring(indexStart, indexEnd) : The substring() method returns a substring of the string from the specified start index up to the end index but excluding the char at end index.

    In the above example, str.substring(0, 9) returns the substring "JavaScrip". Please note that the method returned the substring from index 0 to 8 of the string "JavaScript is fun.". The char at the index 9 is not included in the substring. console.log(str.substring(4, 17)) returns the substring starting from index 4 and ending at 16 (excluding the index 17).


  • toLowerCase() : The toLowerCase() method converts all characters of the string to lowercase.


  • toUpperCase() : The toUpperCase() method converts all characters of the string to uppercase.


  • trim() : The trim() method removes whitespace from the both ends of a string(from start and end).

    In the above example, str.trim() removes the whitespaces before and after "JavaScript" in the string " JavaScript ".


  • startsWith(searchString, startPosition) : The startsWith() method determines whether the string begins with the characters of the specified string and returns Boolean value. The argument 'startPosition' is optional and default value is 0.

    In the above example, str.startsWith("Java") returns true as the string begins with the specified substring "Java". str.startsWith("Script") returns false as the string does not begins with the specified substring "Script". str.startsWith("Script", 4) returns true as the string begins with the specified substring "Script" at index 4.


  • endsWith(searchString, length) : The endsWith() method determines whether the string ends with the characters of the specified string and returns Boolean value. The argument 'length' is optional and default value is the length of the string. The 'length' is the position at which searchString is expected to be found (the index of searchString's last character plus 1).

    In the above example, str.endsWith("fun") returns true as the string ends with the specified substring "fun". str.endsWith("for") returns false as the string does not ends with the specified substring "for". str.endsWith("for", 17) returns true as the string ends with the specified substring "for" at index 17 (the index of last character of "for" is 16 plus 1).


  • repeat(count) : The repeat() method returns a new string with a specified number of copies of the string. The argument 'count' specifies the number of copies of the string.

    In the above example, str.repeat(2) returns a new string with 2 copies of the string "fun! ". While str.repeat(3) returns a new string with 3 copies of the string "fun! ".


  • replace(searchValue, newValue) : The replace() method replaces the first occurrence of a specified value with another new value.

    In the above example, str.replace("fun", "awesome") replaces the first "fun" of the string "JavaScript is fun, fun, and fun." with "awesome" and returns new string "JavaScript is awesome, fun, and fun".


  • replaceAll(searchValue, newValue) : The replaceAll() method replaces all occurrences of a specified value in the string with another specified new value.

    In the above example, str.replaceAll("fun", "awesome") replaces all occurrences of "fun" in the string "JavaScript is fun, fun, and fun" with "awesome" and returns new string "JavaScript is awesome, awesome, and awesome".


  • padStart(targetLength, padString : The padStart() method pads the current string at the starting with another string (padString) until the resulting string reaches the specified target length. The argument 'targetLength' is the length of new string and the argument 'padString' is the string that will be added at the beginning of the string to complete the length of the new string.

    In the above example, str.padStart(3, "0") pads "6" at the beginning with "00" to complete the length of the new string and return the string "006" whose length is 3 as specified.


  • padEnd(targetLength, padString) : The padEnd() method pads the current string at the end with another string (padString) until the resulting string reaches the specified target length. The argument 'targetLength' is the length of new string and the argument 'padString' is the string that will be added at the end of the string to complete the length of the new string.

    In the above example, str.padEnd(3, "0") pads "6" at the end with "00" to complete the length of the new string and return the string "600" whose length is 3 as specified.


  • localeCompare(compareString) : The localeCompare() method returns a number indicating whether this string comes before, or after, or is the same as the given string in sort order.

    In the above example, str1.localeCompare(str2) returns number -1 indicating that 'a' comes before 'c'.


JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Editor. Create more JavaScript strings and practice using different string methods in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Editor
JavaScript Code Output