Table of Contents
What are strings in JavaScript?
A string can be any text inside double or single quotes. JavaScript strings are used for storing or manipulating text.
Strings in JavaScript are primitive data types, which means they are unchanging (altered)!
Primitive data types characteristics:
- A primitive is not an object and has no methods of its own.
- All primitives are immutable, meaning they cannot be altered
Read more here about JavaScript Primitive Data Types
How to work create a string in JavaScript?
In JavaScript, there are three ways to write a string.
You can use single quotes (‘ ‘), double quotes (” “), or with backticks (` `) (Template literals).
There is no preference between using single or double quotes to strings, it basically means the same thing.
However, the type of quote used must match on both sides; also You can use quotes inside a string, as long as they don’t match the quotes surrounding the string.
A string literal is the string as it is written in the source code, including quotations.
A string value is what we see in the output, and does not include quotations.
let str = "It's Not The Same"; console.log(str); //It's Not The Same
Template literals (Template strings)
Template literals are a new feature introduced in ECMAScript 2015/ ES6.
Template literals are enclosed by the backtick (` `) character instead of double or single quotes.
Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).
Before ES6, template literals were called template strings.
let name = "webpedia"; let text = `Welcome to ${name}`; console.log(text);
Important!
We’re not limited to just inserting variables into strings.
We can put any JavaScript expressions we want inside the two brackets.
Multi-line Strings
Any newline characters inserted in the source are part of the template literal.
Using normal strings, you would have to use the following syntax in order to get multi-line strings:
console.log('string text line 1\n' + 'string text line 2'); // "string text line 1 // string text line 2"
Using template literals, you can do the same like this:
console.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2"
Read more here about Template literals
String Concatenation
Prior to ES6, the old way to concatenate strings together was by using the string concatenation operator ( + ).
When is used on strings, the + operator is named the concatenation operator.
let str1 = "Hello"; let str2 = "world"; console.log(str1 + " " + str2); //Hello world
Adding a number to a string will return a string.
let str1 = "Hello"; let str2 = 5; console.log(str1 + " " + str2); //hello 5
Using + operator to concatenate strings it’s ok, but it becomes difficult when we need to build multi-line strings!
As an alternative to using the string concatenation operator ( + ), you can use the String’s concat() method, but both are difficult to use when it comes to build multi-line strings.
const str1 = 'Hello'; const str2 = 'World'; console.log(str1.concat(' ', str2)); // "Hello World"
String Methods and Properties
String Length
To find the length of a string, use the built-in length property.
let str = "It's Not The Same"; console.log(str.length); //17
Escaping Strings in JavaScript
Because the type of quote used to create a string must match on both sides, for example, the string ‘It’s Not The Same’ will throw a SyntaxError:
In order to avoid this error, You can use:
Opposite string syntax
const str3 = "It's Not The Same"; console.log(str3); //It's Not The Same
Use the backslash escape character
The backslash (\) escape character turns special characters into string characters.
const str4 = 'It\'s Not The Same'; console.log(str4); //It's Not The Same
Use template literals
const str5 = `It\'s Not The Same`; console.log(str5); //It's Not The Same
Strings Can also be Objects in JavaScript
Strings can be created as primitives, from string literals, or as objects, using the String() constructor.
const str6 = new String("Hello webpedia"); console.log(str6); //[String: 'Hello webpedia']
But it is not recommended to create strings as objects. It slows down execution speed.
const str6 = new String("Hello webpedia"); const str7 = "Hello webpedia"; console.log(str6 == str7); //true because str6 and str7 have equal values
const str6 = new String("Hello webpedia"); const str7 = "Hello webpedia"; console.log(str6 === str7); //false because str6 and str7 have equal values, but they are different data types
=== operator expects equality in both data type and value.
const str6 = new String("Hello webpedia"); const str7 = "Hello webpedia"; console.log(typeof (str6)); //object console.log(typeof (str7)); //string
Comparing two JavaScript objects will always return false!
const str8 = new String("Hello webpedia"); const str9 = new String("Hello webpedia"); console.log(str8 == str9); //false str8 and str9 are both objects
Character access
There are two ways to access an individual character in a string.
The first is the charAt() method:
console.log('hello'.charAt(1)); // e
The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:
console.log('hello'[1]); // e
Comparing strings
In JavaScript, you can use the < and > operators to compare strings.
The strings are compared letter-by-letter.
The algorithm to compare two strings is simple:
- Compare the first character of both strings;
- If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. It’s done.
- Otherwise, if both strings’ first characters are the same, compare the second characters the same way;
- If both strings end at the same length, then they are equal;
let a = 'a' let b = 'b' if (a < b) { console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } // a is less than b
Uppercase Letters − A – Z having ASCII values from 65 – 90.
Lowercase Letter − a – z having ASCII values from 97 – 122.
Numeric values − 0 – 9 having ASCII values from 48 – 57
a is greater than A
let a = 'a' let b = 'A' if (a < b) { console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } // a is greater than A
JavaScript String methods
toLowerCase() Method
The toLowerCase() method converts a string to lowercase letters.
The toLowerCase() method does not change the original string.
let str10 = "Hello Webpedia"; console.log(str10.toLowerCase()); // hello webpedia console.log(str10); // Hello Webpedia
split() Method
Split a string into an array of substrings, and returns the new array.
If an empty string (“”) is used as the separator, the string is split between each character.
The split() method does not change the original string.
console.log("hello".split("")); //[ 'h', 'e', 'l', 'l', 'o' ]
join() Method
The join() method returns an array as a string.
The elements will be separated by a specified separator. The default separator is a comma (,).
The join() method does not change the original string.
console.log(['h', 'e', 'l', 'l', 'o'].join()); //h,e,l,l,o
To convert the array to string without commas, use join(“”).
console.log(['h', 'e', 'l', 'l', 'o'].join("")); //hello
JavaScript Strings exercises and examples
Reverse a string
Reverse a string s using the split, reverse, and join methods.
function reverseString(s) { try { s = s.split("").reverse().join(""); } catch (err) { console.log(err.message) } finally { console.log(s); } } reverseString("hello webpedia"); //aidepbew olleh
steps
- Split the string into an array of characters using split() method;
- Reverse the array using reverse() method;
- Convert the array back to string using join() method;
Hello there!
I hope you find this post useful!I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.
If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!