A string
is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.
As strings are the way we display and work with text, and text is our main way of communicating and understanding through computers, strings are one of the most fundamental concepts of programming to be familiar with.
Creating and Viewing the Output of Strings
In JavaScript, there are three ways to write a string — they can be written inside single quotes(' ')
, double quotes (" ")
, or backticks (
)
. The type of quote used must match on both sides, however it is possible that all three styles can be used throughout the same script.
Strings using double quotes and single quotes are effectively the same. As there is no convention or official preference for single- or double-quoted strings, all that matters is keeping consistent within project program files.
'This string uses single quotes.';
"This string uses double quotes.";
The third and newest way to create a string is called a template literal. Template literals use the backtick (also known as a grave accent) and work the same way as regular strings with a few additional bonuses, which we will cover in this article.
`This string uses backticks.`;
The easiest way to view the output of a string is to print it to the console, with console.log()
:
console.log("This is a string in the console.");
Output
This is a string in the console.
Another simple way to output a value is to send an alert popup to the browser with alert()
:
alert("This is a string in an alert.");
alert()
is a less common method of testing and viewing output, as it can quickly become tedious to close the alerts.
Storing a String in a Variable
Variables in JavaScript are named containers that store a value, using the keywords var, const or let. We can assign the value of a string to a named variable.
const newString = "This is a string assigned to a variable.";
Now that the newString variable contains a string, we can reference it and print it to the console.
console.log(newString);
This will output the string value.
Output
This is a string assigned to a variable.
🛑 Using variables to stand in for strings
, it is not necessary to retype a string each time we want to use it, making it simpler for us to work with and manipulate strings within our programs.
String Concatenation
🛑 Concatenation means joining two or more strings together to create a new string. In order to concatenate, we use the concatenation operator, represented by a + symbol. The + symbol is also the addition operator when used with arithmetic operations.
👉 There are 3 ways to concatenate strings in JavaScript. In this tutorial, you'll the different ways and the tradeoffs between them.
The +
Operator
👉 The same+
operator you use for adding two numbers can be used to concatenate two strings.
const str = 'Hello' + ' ' + 'World';
str; // 'Hello World'
👉 You can also use +=
, where a += b
is a shorthand for a = a + b
.
let str = 'Hello';
str += ' ';
str += 'World';
str; // 'Hello World'
🛑 If the left hand side of the +
operator is a string, JavaScript will coerce the right hand side to a string. That means it is safe to concatenate objects, numbers, null, and undefined.
let str = 'Values: ';
str += 42;
str += ' ';
str += {};
str += ' ';
str += null;
str; // 'Values: 42 [object Object] null'
[Array].join()
🚀 The[Array].join()
function creates a new string from concatenating all elements in an array. For example:
['Hello', ' ', 'World'].join(''); // 'Hello World'
🚀 The first parameter to join() is called the separator. By default, the separator is a single comma ','
.
['a', 'b', 'c'].join(); // 'a,b,c'
🚀 You can pass in any separator you want. Separators make [Array].join()
the preferred choice for concatenating strings if you find yourself repeating the same character over and over again. For example, you can use ' '
as the separator to join an array of words:
// 'This happened the night before Christmas'
['This' 'happened', 'the', 'night', 'before', 'Christmas'].join(' ');
- Or you can use
'/'
to join together URL fragments:
// 'study.js/fundamentals/string-concat'
['study.js', 'fundamentals', 'string-concat'].join('/');
🚀 Separators make Array.join()
a very flexible way to concatenate strings. If you want to join together a variable number of strings, you should generally usejoin()
rather than a for loop
with+
.
String.concat()
JavaScript strings have a built-in concat()
method. The concat()
function takes one or more parameters, and returns the modified string. Strings in JavaScript are immutable
, so concat()
doesn't modify the string in place.
const str1 = 'Hello';
const str2 = str1.concat(' ', 'World');
// 'Hello'. Strings are immutable, so `concat()` does not modify `str1`
str1;
// 'Hello World'
str2;
The concat()
function is rarely used because it has more error cases than the + operator. For example, you would get unexpected behavior if you call concat() on a value that happens to be an array. You should use + instead of concat() unless you have a very good reason.
If you must use concat()
, it is usually best to call it on an empty string:
''.concat('Hello', ' ', 'World');
"The car" + "is fast";
// output: "The caris fast"
Concatenation joins the strings end to end, combining them and outputting a brand new string value. If we would like to have a space between the words car
and fast
, we would need to include a whitespace character
in one of the strings:
"The car " + "is fast";
// output: "The car is fast"
🛑 Remember : We join strings and variables containing string values with concatenation.
const book = "The Lost Symbol";
const author = "Dan Brown";
const favBook = "My favorite book is " + book + " by " + author + ".";
// output: My favourite book is The lost Symbol by Dan Brown.
🛑 When combining two or more strings through concatenation we are creating a new string that we can use throughout our program.
Variables in Strings with Template Literals
🛑 One special feature of the template literal feature is the ability to include expressions and variables within a string. Instead of having to use concatenation, we can use the ${}
syntax to insert a variable.
const book = "The Lost Symbol";
const author = "Dan Brown";
const favBook = `My favorite book is ${book} by ${author}.`;
Including expressions in template literals is another way to accomplish the same result.
Instance methods are methods that are run on a string type.
A string offers a few unique methods you can use:
charAt(i)
charCodeAt(i)
codePointAt(i)
concat(str)
endsWith(str)
includes(str)
indexOf(str)
lastIndexOf(str)
localeCompare()
match(regex)
normalize()
padEnd()
padStart()
repeat()
replace(str1, str2)
search(str)
slice(begin, end)
split(separator)
startsWith(str)
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
trimEnd()
trimStart()
valueOf()
Top comments (0)