JavaScript ES6 Strings
Strings store a series of characters. Strings are commonly used to hold text based values like a person's name or a product description.
Any text inside either double or single quotes is considered a string in JavaScript.
let firstName = "John"
let lastName = 'Doe'
Defining Strings
You can define a string like this:
let firstName = "John"
You can also create a string object with the String() constructor:
let firstName = new String("John")
String Methods
Below are a list of methods supported by the String object in JavaScript.
length
The length method returns the number of characters in a string, including spaces:
let myString = "hello"
myString.length
//returns 5
charAt()
The charAt() function returns the character at the specified index:
let myString = "hello"
myString.charAt(2)
//returns 'l'
charCodeAt()
Same as charAt(), but returns a unicode representation of the character at that given index:
let myString = "hello"
myString.charCodeAt(2)
//returns 108
concat()
The concat() method combines strings:
let firstName = "John"
let lastName = " Doe"
firstName.concat(lastName)
//returns 'John Doe'
indexOf()
The indexOf() method returns the index of the first occurance of the specified value. If no matches are found, -1 is returned:
let firstName = "John"
firstName.indexOf('o')
//returns 1
firstName.indexOf('z')
//returns -1
lastIndexOf()
Same as indexOf(), but returns the index of the last occurance instead of the first occurance:
let fruit = "banana"
fruit.lastIndexOf('a')
//returns 5
fruit.lastIndexOf('z')
//returns -1
localeCompare()
The localeCompare() method compares the order of a string argument to that of the string itself. It returns -1 if there is no match and the argument string comes after the string object, 0 if the string matches 100%, and 1 if there is no match but the argument string comes before the string object:
let myString = "hello world"
myString.localeCompare("goodbye")
//returns 1 since "goodbye" comes before "hello world" and does not match
myString.localeCompare("zed")
//returns -1 since there is no match and the argument "zed" comes after "hello world" in sorted order
myString.localeCompare("hello world")
//returns 0 since it's a match!
match()
The match() method compares a string to a regular expression and returns an array with all occurances of the match:
let fruit = 'banana'
fruit.match(/a/g)
//returns ['a','a','a']
fruit.match(/z/)
//returns null
replace()
The replace() method replaces the characters in a string based on a regular expression:
let myString = "hello world"
myString.replace(/l/g, "z")
//returns 'hezzo worzd'
myString.replace(/l/, "z")
//returns 'hezlo world'
search()
The search() method returns the index of a provided regular expression within the string. If there is no match, -1 is returned:
let myString = "hello world"
myString.search(/world/)
//returns 6
myString.search(/zed/)
//returns -1
slice()
The slice() method returns a substring with the specified start and end index:
let myString = "hello world"
myString.slice(0,2)
//returns 'he'
myString.slice(2,4)
//returns 'll'
split()
The split() method returns an array of substrings based on a separator:
let myString = "hello world"
myString.split(" ")
//returns ['hello', 'world']
myString.split("l")
//returns ['he', '', 'o wor', 'd']
myString.split("l", 2)
//returns ['he', '']
substr()
The substr() method returns a substring based on a start index and the number of characters to return:
let myString = "hello world"
myString.substr(-1)
//returns 'd'
myString.substr(0,5)
//returns 'hello'
myString.substr(2,3)
//returns 'llo'
substring()
Similar to substr(), the key difference being the second argument. With substring(), the second argument specifies the end index rather than length:
let myString = "hello world"
myString.substring(2,3)
//returns 'l'
toLowerCase()
The toLowerCase() method returns a string with all lower case characters:
let myString = "Hello World"
myString.toLowerCase()
//returns 'hello world'
toUpperCase()
The toUpperCase() method returns a string with all upper case characters:
let myString = "Hello World"
myString.toUpperCase()
//returns 'HELLO WORLD'
valueOf()
The valueOf() method returns the primitive value of a string object:
let myString = "hello world"
myString.valueOf()
//returns 'hello world'
startsWith()
The startsWith() method returns true if the string starts with the supplied argument. This method optionally takes a second parameter to specify the position to start checking:
let myString = "hello world"
myString.startsWith('hel')
//returns true
myString.startsWith('el')
//returns false
myString.startsWith('el', 1)
//returns true
endsWith()
The endsWith() method returns true if the string ends with the supplied argument. This method optionally takes a second parameter to specify the length to check:
let myString = "hello world"
myString.endsWith('world')
//returns true
myString.endsWith('world', 11)
//returns true
myString.endsWith('world', 10)
//returns false
includes()
The include() method returns true if the supplied argument is in the string. This method optionally takes a second parameter to specify the start position:
let myString = "hello world"
myString.includes('world')
//returns true
myString.includes('world', 7)
//returns false
repeat()
The repeat() method returns a new string repeated based on the supplied count argument:
let myString = "hello world"
myString.repeat(3)
//returns 'hello worldhello worldhello world'
Template Literals
ES6 introduces the concept of template literals in JavaScript. With template literals, you can embed expressions and define multi-line strings.
You define template literals with the backtick character ` rather than quotes:
let myLiteral = `this is a literal`
String Interpolation
Template literals can hold placeholders for values with interpolation:
let myAge = 30
let myName = 'John'
let statement = `hello, my name is ${myName} and I am ${myAge} years old.`
console.log(statement)
//logs 'hello, my name is John and I am 30 years old'
Notice how we use the ${} syntax to insert other variables into our template literal.
Multiline Strings
Template literals also allow you to define strings over multiple lines:
let myString = `this is a string that
takes up multiple lines
and stores the value
as myString`
Other Methods
String.fromCodePoint()
This method returns a new string based on the specified sequence of unicode code points:
let myString = String.fromCodePoint(102, 110)
console.log(myString)
//logs 'fn'
String.raw()
You can use the String.raw() method to ignore backslashes:
let myString = `hello
world`
console.log(myString)
//returns 'hello
world'
Conclusion
Understanding how to create and manipulate strings is a powerful skill in JavaScript programming. Use strings to represent sets of characters as variables.