We use JavaScript string data type is used to store the textual data. It is a primitive data type in JavaScript. We enclose string data in double-quotes (“) or single quotes (‘). We can also define them using the template literal syntax or back-tick. such strings are called template strings, The template strings can be used to create multi-line strings, strings with embedded expressions & Tagged Template strings. The JavaScript also has an String
object, which is a wrapper around a primitive string
. In this tutorial, we learn about JavaScript strings. We also find out the difference between String vs string. Finally, we also look at the list of JavaScript string functions.
Table of Contents
Creating Strings
There are three ways to create a primitive string
.
- String Literals
- Using Global String function
- Template literal syntax or back-tick
String Literals
String literals are strings inside a double (” “) or single (‘ ‘) quote. There is no difference between them.
The following example creates a string with value Hello World
using a single quote
1 2 3 4 5 | let message='Hello World'; //in single quote console.log(message); //Hello World console.log(typeof(message)) //string |
You can also use a double quote.
1 2 3 4 5 | let message="Hello World"; //in double quote console.log(message); //Hello World console.log(typeof(message)) //string |
But mixing both results in an error. The following example throws an error because we started with a double quote and ended with a single quote
1 2 3 | let message="Hello World'; //Invalid or unexpected token |
But we can include a single quote inside a double quote (or vice versa). In this example, the single quote is now part of the string
1 2 3 4 5 6 7 8 9 | let message1="Hello 'World'"; //Ok let message="Hello 'World"; //ok let message1='Hello "World"'; //Ok let message1='Hello World"'; //Ok |
But the following results in an error
1 2 3 | let message="Hello "World""; // Unexpected identifier |
String Function
We can also use the global String function to create a primitive string
as shown below.
1 2 3 4 5 6 7 8 9 | let color=String("red"); console.log(color); console.log(typeof(color)) **** output **** red string |
Template Literal (Template String)
The Template Literal or Template strings are strings, which are enclosed in a back-tick (`
). They bring several other features like
The following is an example of a multiline string.
1 2 3 4 5 | let sentence =`Javascript is the scripting language, that we use to make web pages interactive. It is written in plain text on the HTML page and runs in the browser` console.log(sentence); |
Long single-line strings
The long single-line strings take up the entire screen width. You can break them into multiple lines using the + operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | let longString = "This is an example of long single line of string and it goes out of my editor screen so i need to wrap it"; let longString1 = "This is an example of long single line of string " + "and it goes out of my editor screen " + "so i need to wrap it"; console.log(longString); console.log(longString1); *** output *** This is an example of long single line of string and it goes out of my editor screen so i need to wrap it |
Another way is to use the \
at the end of the line, which indicates that the line continues on the next line.
1 2 3 4 5 6 7 8 9 10 | let longString2 = "This is an example of long single line of string \ and it goes out of my editor screen \ so i need to wrap it"; console.log(longString2) *** output *** This is an example of long single line of string and it goes out of my editor screen so i need to wrap it |
Any leading spaces also become part of thestring
.
1 2 3 4 5 6 7 8 9 10 | let longString2 = "This is an example of long single line of string \ and it goes out of my editor screen \ so i need to wrap it"; console.log(longString2) *** output *** This is an example of long single line of string and it goes out of my editor screen so i need to wrap it |
Primitive string vs Object String
JavaScript has two string data types. The one is a string
(lowercase) & the other one is String
(S is uppercase)
The string
is a primitive data type. It is the one you must use. The primitive data type does not have properties or methods.
The String
is a wrapper object around primitive string
. It is created by using the syntax new String("")
(constructor function). The objects have properties or methods.
1 2 3 4 5 6 7 8 9 | var str1= new String("Created with String") //str1 is a String object console.log(str1); console.log(typeof(str1)) **** output **** [String: 'Created with String'] object |
JavaScript String function creates a primitive string
. But String object can be created only with new String()
.
1 2 3 4 5 6 7 8 9 10 | var strPrim = "I am primitive"; //primitive var strGlb=String("I am a primitive string created using String method") //primitive var strObj= new String("I am a object") //object console.log(typeof(strPrim)) //string console.log(typeof(strGlb)) //string console.log(typeof(strObj)) //object |
String Functions
As mentioned earlier, the strings are primitive types and do not support methods & properties. But as shown in the following example shows it has a method indexOf
.
1 2 3 4 5 6 7 8 | let strValue="This is a primitive string. But is has properties & methods" let pos=strValue.indexOf("primitive") console.log(pos); ***output*** 10 |
That is because string
primitives are coerced into a String
object in order to access the method indexOf
. The object is used only temporarily and is garbage collected once the method call is returned.
Methods
Method | Description |
---|---|
charAt | Returns the character at the specified index. @param pos — The zero-based index of the desired character |
charCodeAt | Returns the Unicode value of the character at the specified location. @param index — The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. |
codePointAt | eturns a nonnegative integer Number less than 1114112 (0x110000) that is the code point value of the UTF-16 encoded code point starting at the string element at position pos in the String resulting from converting this object to a String. If there is no element at that position, the result is undefined. If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. |
concat | Returns a string that contains the concatenation of two or more strings. @param strings — The strings to append to the end of the string. |
endsWith | Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at endPosition – length(this). Otherwise returns false. |
includes | Returns true if searchString appears as a substring of the result of converting this object to a String, at one or more positions that are greater than or equal to position; otherwise, returns false. @param searchString — search string @param position — If position is undefined, 0 is assumed, so as to search all of the String. |
indexOf | Returns the position of the first occurrence of a substring. @param searchString — The substring to search for in the string @param position — The index at which to begin searching the String object. If omitted, search starts at the beginning of the string |
lastIndexOf | Returns the last occurrence of a substring in the string. @param searchString — The substring to search for. @param position — The index at which to begin searching. If omitted, the search begins at the end of the string. |
length | Returns the length of a String object. |
localeCompare | Determines whether two strings are equivalent in the current locale. @param that — String to compare to target string |
match | Matches a string with a regular expression, and returns an array containing the results of that search. @param regexp — A variable name or string literal containing the regular expression pattern and flags. |
normalize | Returns the String value result of normalizing the string into the normalization form named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. @param form — Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default is "NFC" |
repeat | Returns a String value that is made from count copies appended together. If count is 0, the empty string is returned. @param count — number of copies to append |
replace | Replaces text in a string, using a regular expression or search string. @param searchValue — A string to search for. @param replaceValue — A string containing the text to replace for every successful match of searchValue in this string. |
search | Finds the first substring match in a regular expression search. @param regexp — The regular expression pattern and applicable flags. |
slice | Returns a section of a string. @param start — The index to the beginning of the specified portion of stringObj. @param end — The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. If this value is not specified, the substring continues to the end of stringObj. |
split | Split a string into substrings using the specified separator and return them as an array. @param separator — A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. @param limit — A value used to limit the number of elements returned in the array. |
startsWith | Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false. |
substr | Gets a substring beginning at the specified location and having the specified length. @param from — The starting position of the desired substring. The index of the first character in the string is zero. @param length — The number of characters to include in the returned substring. |
substring | Returns the substring at the specified location within a String object. @param start — The zero-based index number indicating the beginning of the substring. @param end — Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. If end is omitted, the characters from start through the end of the original string are returned. |
toLocaleLowerCase | Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. |
toLocaleUpperCase | Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale |
toLowerCase | Converts all the alphabetic characters in a string to lowercase |
toString | Returns a string representation of a string. |
toUpperCase | Converts all the alphabetic characters in a string to uppercase |
trim | Removes the leading and trailing white space and line terminator characters from a string. |
valueOf | Returns the primitive value of the specified object. |
Method | Description |
---|---|
anchor | Returns an <a> HTML anchor element and sets the name attribute to the text value @param name |
big | Returns a <big> HTML element |
blink | Returns a <blink> HTML element |
bold | Returns a <b> HTML element |
fixed | Returns a <tt> HTML element |
fontcolor | Returns a <font> HTML element and sets the color attribute value |
fontsize | Returns a <font> HTML element and sets the size attribute value |
italics | Returns an <i> HTML element |
link | Returns an <a> HTML element and sets the href attribute value |
small | Returns a <small> HTML element |
strike | Returns a <strike> HTML element |
sub | Returns a <sub> HTML element |
sup | Returns a <sup > HTML element |
Summary
JavaScript string
is a primitive data type. The String
is an object which is a wrapper around primitive string
We can use string literals (i.e. single quote or double quote), global string function, or use template literal syntax to create a primitive string. We use template strings to create multi-line strings, strings with embedded expressions & Tagged Template strings, etc.
References
Read More