- JavaScript Basics
- JavaScript Tutorial
- JavaScript: where to write
- JavaScript: how to display
- JavaScript: keywords
- JavaScript: comments
- JavaScript: variables
- JavaScript: operators
- JavaScript: data types
- JavaScript Conditional Statements
- JavaScript: if-else
- JavaScript: switch
- JavaScript: for loop
- JavaScript: while loop
- JavaScript: do-while loop
- JavaScript: break and continue
- JavaScript Popup Boxes
- JavaScript: alert box
- JavaScript: confirm box
- JavaScript: prompt box
- JavaScript Popular Topics
- JavaScript: functions
- JavaScript: innerHTML
- JavaScript: getElementById()
- JavaScript: getElementsByClassName()
- JavaScript: getElementsByName()
- JavaScript: getElementsByTagName()
- JavaScript: querySelector()
- JavaScript: querySelectorAll()
- JavaScript: document.write()
- JavaScript: console.log()
- JavaScript: boolean
- JavaScript: events
- JavaScript: Math object
- JavaScript: Math.random()
- JavaScript: Number()
- JavaScript: parseInt()
- JavaScript: parseFloat()
- JavaScript Arrays
- JavaScript: array
- JavaScript: find length of array
- JavaScript: add element at beginning
- JavaScript: add element at end
- JavaScript: remove first element
- JavaScript: remove last element
- JavaScript: get first index
- JavaScript: get last index
- JavaScript: reverse an array
- JavaScript: sort an array
- JavaScript: concatenate arrays
- JavaScript: join()
- JavaScript: toString()
- JavaScript: from()
- JavaScript: check if value exists
- JavaScript: check if array
- JavaScript: slice an array
- JavaScript: splice()
- JavaScript: find()
- JavaScript: findIndex()
- JavaScript: entries()
- JavaScript: every()
- JavaScript: fill()
- JavaScript: filter()
- JavaScript: forEach()
- JavaScript: map()
- JavaScript Strings
- JavaScript: string
- JavaScript: length of string
- JavaScript: convert to lowercase
- JavaScript: convert to uppercase
- JavaScript: string concatenation
- JavaScript: search()
- JavaScript: indexOf()
- JavaScript: search() vs. indexOf()
- JavaScript: match()
- JavaScript: match() vs. search()
- JavaScript: replace()
- JavaScript: toString()
- JavaScript: String()
- JavaScript: includes()
- JavaScript: substr()
- JavaScript: slice string
- JavaScript: charAt()
- JavaScript: repeat()
- JavaScript: split()
- JavaScript: charCodeAt()
- JavaScript: fromCharCode()
- JavaScript: startsWith()
- JavaScript: endsWith()
- JavaScript: trim()
- JavaScript: lastIndexOf()
- JavaScript Date and Time
- JavaScript: date and time
- JavaScript: Date()
- JavaScript: getFullYear()
- JavaScript: getMonth()
- JavaScript: getDate()
- JavaScript: getDay()
- JavaScript: getHours()
- JavaScript: getMinutes()
- JavaScript: getSeconds()
- JavaScript: getMilliseconds()
- JavaScript: getTime()
- JavaScript: getUTCFullYear()
- JavaScript: getUTCMonth()
- JavaScript: getUTCDate()
- JavaScript: getUTCDay()
- JavaScript: getUTCHours()
- JavaScript: getUTCMinutes()
- JavaScript: getUTCSeconds()
- JavaScript: getUTCMilliseconds()
- JavaScript: toDateString()
- JavaScript: toLocaleDateString()
- JavaScript: toLocaleTimeString()
- JavaScript: toLocaleString()
- JavaScript: toUTCString()
- JavaScript: getTimezoneOffset()
- JavaScript: toISOString()
- JavaScript Regular Expression
- JavaScript: regular expression
- JavaScript: RegEx . (dot)
- JavaScript: RegEx \w and \W
- JavaScript: RegEx \d and \D
- JavaScript: RegEx \s and \S
- JavaScript: RegEx \b and \B
- JavaScript: RegEx \0
- JavaScript: RegEx \n
- JavaScript: RegEx \xxx
- JavaScript: RegEx \xdd
- JavaScript: RegEx quantifiers
- JavaScript: RegEx test()
- JavaScript: RegEx lastIndex
- JavaScript: RegEx source
- JavaScript Programs
- JavaScript Programs
JavaScript String (with Examples)
A string in JavaScript is a sequence of characters used to hold or store textual data.
Create a string in JavaScript
To create a string in JavaScript, follow any of the two ways:
- Create strings directly using string literals or as string primitives.
- Create a string using the String() constructor as an object
For example:
let x = "codescracker"; let y = "JavaScript is Fun.";
Or
let x = new String("codescracker"); let y = new String("JavaScript is Fun.");
A string in JavaScript can contain zero, one, or more sequences of characters. Also, string literals in JavaScript will be in single or double quotes. For example:
<!DOCTYPE html> <html> <body> <p id="para1"></p> <p id="para2"></p> <p id="para3"></p> <p id="para4"></p> <p id="para5"></p> <p id="para6"></p> <p id="para7"></p> <script> let myString1 = ""; let myString2 = ''; let myString3 = "c"; let myString4 = "5"; let myString5 = 'g'; let myString6 = "I'm from Boston"; let myString7 = "Where are you from?"; document.getElementById("para1").innerHTML = typeof(myString1); document.getElementById("para2").innerHTML = typeof(myString2); document.getElementById("para3").innerHTML = typeof(myString3); document.getElementById("para4").innerHTML = typeof(myString4); document.getElementById("para5").innerHTML = typeof(myString5); document.getElementById("para6").innerHTML = typeof(myString6); document.getElementById("para7").innerHTML = typeof(myString7); </script> </body> </html>
Please note: The typeof() method returns the type of value or variable defined as its argument.
How do I quote a substring in a JavaScript string?
If the quote you're going to use to quote any substring inside a string does not match the quote used to quote the string literal, then it will be okay. For example:
<!DOCTYPE html> <html> <body> <p id="para1"></p> <p id="para2"></p> <script> let myString1 = "Hey, I am from 'Boston'. Where are you from?"; let myString2 = 'Hey, I am from "Boston". Where are you from?'; document.getElementById("para1").innerHTML = myString1; document.getElementById("para2").innerHTML = myString2; </script> </body> </html>
But sometimes we find that the quote of the string literal is the same as the quote that we're needing to use. For example:
'Hey, I'm from Boston.'
Notice the single quote in between I and m. The solution is to use an escape sequence. For example:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let mystr = 'Hey, I\'m from Boston.'; document.getElementById("xyz").innerHTML = mystr; </script> </body> </html>
That is, the backslash character (\) is used in all these similar scenarios. Also, if you need to include a backslash in the string, then, in that case, use double backslashes (\\). For example:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> let mystr = 'Hello\\Hi'; document.getElementById("xyz").innerHTML = mystr; </script> </body> </html>
JavaScript Escape Characters
Here is the list of escape characters used in JavaScript:
- \ converts some special characters like (' and "") into strings.
- \b moves the cursor backward (one position or character left). The \b character does not erase anything while moving the cursor backward.
- \f loads the next page while working with printers or clears the screen while working in some terminal emulators.
- \v position the form to the next line tab stop. The size of the lines will be determined by the default size of the tab while working on that particular software.
- \n inserts a newline or moves the cursor to the newline, so that the next character starts with a newline. While working with HTML, it doesn't work. The BR tag works instead. But using \n inserts a new line in the source.
- \r is similar to \n. But it depends on the operating system. Some treats \n\r as newline, some treats \n as newline, whereas some treats \r\n as newline.
- \t inserts a horizontal tab (a space of around 1-4 or some other number of characters, depending on the size of the horizontal tab).
Since these escape characters are developed to work with printers, fax machines, etc., this does not make sense, especially when working with HTML. Therefore, I am unable to show you examples regarding these characters. But remember its description.
JavaScript String Methods
Here is the list of methods that can be used with JavaScript strings, along with their descriptions:
- toLowerCase: convert the specified string to lowercase.
- toUpperCase: convert the specified string to uppercase.
- concat: concatenate or join two or more strings.
- search: searches a substring (value) in a string using a regular expression.
- indexOf(): find the position or index number of a specified value (or substring) in a string.
- match(): match a string with or using a regular expression.
- replace(): replace a string using either the string itself or a regular expression.
- includes(): check whether a string contains a specified substring or not.
- substr(): extract a substring from a specified position in the specified string.
- slice(): extract the required substring from the specified string.
- charAt(): find a character available at a specified position in a specified string.
- repeat(): repeat a string for a given number of times.
- split(): split a specified string into an array.
- charCodeAt(): find the Unicode of a character at a specified index in a specified string.
- fromCharCode(): convert Unicode values to their equivalent characters or strings.
- startsWith(): check if a specified string starts with a specified substring.
- endsWith(): check whether a string ends with a specified substring or not.
- trim(): remove all whitespaces from the beginning and end of the string.
- lastIndexOf(): returns the position of the last occurrence of the specified value in a given string.
Please note: A few methods, which are very rarely used in rare cases, are skipped.
JavaScript String Example
<!DOCTYPE html> <html> <body> <script> let x, res, temp; function myFun() { x = document.getElementById("str").value; temp = document.getElementById("mypara"); temp.style.display = "block"; res = x.toUpperCase(); document.getElementById("result").innerHTML = res; } </script> <p>Enter a String: <input id="str"><br><br> <button onclick="myFun()">Convert to Uppercase</button></p> <p id="mypara" style="display: none;"> Output: <span id="result"></span></p> </body> </html>
Enter a String:
Please note: To find the length of a string in JavaScript, use the string.length property.
« Previous Tutorial Next Tutorial »