- JavaScript Basics
- JS Home
- JS Syntax
- JS Placements
- JS Output
- JS Statements
- JS Keywords
- JS Comments
- JS Variables
- JS var
- JS let
- JS const
- JS var Vs let Vs const
- JS Operators
- JS Arithmetic Operators
- JS Assignment Operators
- JS Comparison Operators
- JS Logical Operators
- JS Bitwise Operators
- JS Ternary Operator
- JS Operator Precedence
- JS Data Types
- JS typeof
- JS Conditional Statements
- JS Conditional Statement
- JS if Statement
- JS if...else Statement
- JS switch Statement
- JS Loops
- JS for Loop
- JS while Loop
- JS do...while Loop
- JS break Statement
- JS continue Statement
- JS break Vs. continue
- JavaScript Popup Boxes
- JS Dialog Box
- JS alert Box
- JS confirm Box
- JS prompt Box
- JavaScript Functions
- JS Functions
- JS setTimeout() Method
- JS setInterval() Method
- JavaScript Events
- JS Events
- JS onclick Event
- JS onload Event
- JS Mouse Events
- JS onreset Event
- JS onsubmit Event
- JavaScript Arrays
- JS Array
- JS Find Length of Array
- JS Add Elements at Beginning
- JS Add Element at End
- JS Remove First Element
- JS Remove Last Element
- JS Get First Index
- JS Get Last Index
- JS Reverse an Array
- JS Sort an Array
- JS Concatenate Arrays
- JS join()
- JS toString()
- JS from()
- JS Check if Value Exists
- JS Check if Array
- JS Slice an Array
- JS splice()
- JS find()
- JS findIndex()
- JS entries()
- JS every()
- JS fill()
- JS filter()
- JS forEach()
- JS map()
- JavaScript Strings
- JS String
- JS Length of String
- JS Convert to Lowercase
- JS Convert to Uppercase
- JS String Concatenation
- JS search()
- JS indexOf()
- JS search() Vs. indexOf()
- JS match()
- JS match() Vs. search()
- JS replace()
- JS toString()
- JS String()
- JS includes()
- JS substr()
- JS Slice String
- JS charAt()
- JS repeat()
- JS split()
- JS charCodeAt()
- JS fromCharCode()
- JS startsWith()
- JS endsWith()
- JS trim()
- JS lastIndexOf()
- JavaScript Objects
- JS Objects
- JS Boolean Object
- JavaScript Math/Number
- JS Math Object
- JS Math.abs()
- JS Math.max()
- JS Math.min()
- JS Math.pow()
- JS Math.sqrt()
- JS Math.cbrt()
- JS Math.round()
- JS Math.ceil()
- JS Math.floor()
- JS Math.trunc
- JS toFixed()
- JS toPrecision()
- JS Math.random()
- JS Math.sign()
- JS Number.isInteger()
- JS NaN
- JS Number()
- JS parseInt()
- JS parseFloat()
- JavaScript Date and Time
- JS Date and Time
- JS Date()
- JS getFullYear()
- JS getMonth()
- JS getDate()
- JS getDay()
- JS getHours()
- JS getMinutes()
- JS getSeconds()
- JS getMilliseconds()
- JS getTime()
- JS getUTCFullYear()
- JS getUTCMonth()
- JS getUTCDate()
- JS getUTCDay()
- JS getUTCHours()
- JS getUTCMinutes()
- JS getUTCSeconds()
- JS getUTCMilliseconds()
- JS toDateString()
- JS toLocaleDateString()
- JS toLocaleTimeString()
- JS toLocaleString()
- JS toUTCString()
- JS getTimezoneOffset()
- JS toISOString()
- JavaScript Browser Objects
- JS Browser Objects
- JS Window Object
- JS Navigator Object
- JS History Object
- JS Screen Object
- JS Location Object
- JavaScript Document Object
- JS Document Object Collection
- JS Document Object Properties
- JS Document Object Methods
- JS Document Object with Forms
- JavaScript DOM
- JS DOM
- JS DOM Nodes
- JS DOM Levels
- JS DOM Interfaces
- JavaScript Cookies
- JS Cookies
- JS Create/Delete Cookies
- JavaScript Regular Expression
- JS Regular Expression
- JS RegEx .
- JS RegEx \w and \W
- JS RegEx \d and \D
- JS RegEx \s and \S
- JS RegEx \b and \B
- JS RegEx \0
- JS RegEx \n
- JS RegEx \xxx
- JS RegEx \xdd
- JS RegEx Quantifiers
- JS RegEx test()
- JS RegEx lastIndex
- JS RegEx source
- JavaScript Advance
- JS Page Redirection
- JS Form Validation
- JS Validations
- JS Error Handling
- JS Exception Handling
- JS try-catch throw finally
- JS onerror Event
- JS Multimedia
- JS Animation
- JS Image Map
- JS Debugging
- JS Browser Detection
- JS Security
- JavaScript Misc
- JS innerHTML
- JS getElementById()
- JS getElementsByClassName()
- JS getElementsByName()
- JS getElementsByTagName()
- JS querySelector()
- JS querySelectorAll()
- JS document.write()
- JS console.log()
- JS instanceof
- JavaScript Programs
- JavaScript Programs
JavaScript String (with Examples)
String in JavaScript is a sequence of characters, used to hold/store textual data.
Create a String in JavaScript
To create a string in JavaScript, follow any of the two ways:
- Create string directly using string literals, as string primitive
- Create string using String() constructor, as object
For example:
let x = "fresherearth"; let y = "JavaScript is Fun.";
Or
let x = new String("fresherearth"); let y = new String("JavaScript is Fun.");
String in JavaScript can contain zero, one, or more sequence of characters. Also a 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/variable defined as its argument.
How to Quote Substring in 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 sometime we find that the quote of the string literal is 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 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 type of similar scenarios. Also, if you need to include a backslash itself 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 are the list of escape characters used in JavaScript:
- \ converts some special character like (' and "") into string.
- \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 lines will be decided 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, next character starts with newline. While working with HTML, it doesn't work. The BR tag work instead. But using \n inserts a new line in the source.
- \r is similar to \n. But it depends on the operating system. As 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 horizontal tab)
Since these escape characters are developed to work with printers, fax machines etc. which does not make sense specially while working with HTML. Therefore I am unable to show you the examples regarding these characters. But remember its description.
JavaScript String Methods
Here are the list of methods that can be used with JavaScript string, along with its description:
- toLowerCase - convert specified string to lowercase
- toUpperCase - convert specified string to uppercase
- concat - concatenate or join two or more strings
- search - searches a substring (value) in a string using regular expression
- indexOf() - find the position or index number of specified value (or substring) in a string
- match() - match a string with/using a regular expression
- replace() - replace a string using either string itself or regular expression
- includes() - check whether a string contains specified substring or not
- substr() - extract substring from specified position in specified string
- slice() - extract required substring from specified string
- charAt() - find character available at specified position in a specified string
- repeat() - repeat a string for n number of times
- split() - split a specified string into an array
- charCodeAt() - find the Unicode of a character at specified index in a specified string
- fromCharCode() - convert Unicode values to its equivalent characters or strings
- startsWith() - check if a specified string starts with specified substring
- endsWith() - check whether a string ends with a specified substring or not
- trim() - remove all whitespaces from beginning and end of the string
- lastIndexOf() - returns the position of last occurrence of 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 string.length property.
« Previous Tutorial Next Tutorial »