DEV Community

Cover image for String Manipulation in JavaScript
Swarnali Roy
Swarnali Roy

Posted on

String Manipulation in JavaScript

In JavaScript, when we want to define any string we must start and end with either a single (' ') or double quote(" "). For example:

let myName = 'My name is Swarnali Roy'
Enter fullscreen mode Exit fullscreen mode

or,

let myName = "My name is Swarnali Roy"
Enter fullscreen mode Exit fullscreen mode

We need to manipulate strings in our codes often and for that we have various ways. Today's post is all about String Manipulation in JavaScript.

🔶 Escaping Literal Quotes with Backslash ( \ )

Sometimes, if we want to include a literal quote: " or ' inside of the string, then how will we manipulate the string? The following two examples will show how it works.

🔹 Example 1: Using a literal quote: double quote (" ") inside of the string which is also started with a double quote("") 👇

let myName = "She said, " My name is Swarnali Roy ".";
console.log(myName);

/*output : let myName = "She said, " My name is Swarnali Roy ".";
                                     ^^
SyntaxError: Unexpected identifier */
Enter fullscreen mode Exit fullscreen mode

The output shows a SyntaxError, as the starting quotation(") is looking for it's closing quotation which is found after "She said, ". So it takes "She said, " as a string. But the other part My name is Swarnali Roy is neither a string nor any syntax because it is outside of the "" and again find the full stop/period(.) within the "".

🔹 Example 2: Using a literal quote: single quote (' ') within a string that is started and ended with "" 👇

let myName = "She said, ' My name is Swarnali Roy '.";
console.log(myName);

//output: She said, ' My name is Swarnali Roy '.
Enter fullscreen mode Exit fullscreen mode

Here, the output shows the expected syntax as we have used single quotation inside double quotation and there is no confusion in starting and ending quotation marks.

This was a simple example, but in a complex string it is not so easy to manipulate a string like this. There comes a concept of escaping literal quotes using a backslash ( \ ) in front of the quote. This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string.

Let's solve the SyntaxError of the Example 1 using this process.

let myName = "She said, \" My name is Swarnali Roy \".";
console.log(myName);

//output: She said, " My name is Swarnali Roy ".
Enter fullscreen mode Exit fullscreen mode

Now, the backslash is separating the literal quote and the quote is appearing inside the string.

🔶 Escape Sequences in Strings

Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters:

◽ It allows us to use characters that may not otherwise be able to type out, such as a newline or tab.
◽ To allow us to represent multiple quotes in a string without JavaScript misinterpreting what we actually mean.

Some important syntax are:
🔹Single Quote : \'
🔹Double Quote : \"
🔹newline : \n
🔹tab : \t
🔹backslash: \\
🔹carriage return : \r
🔹word boundary : \b
🔹form feed: \f

A simple example is 👇

var myName = "She said,\n\t'My name is\nSwarnali Roy'";

/* output: She said,
               'My name is
           Swarnali Roy'. */
Enter fullscreen mode Exit fullscreen mode

🔶 Concatenating Strings with + Operator

🔹 When we use the + operator with a string, it is called the concatenation operator. With this, we can merge/concatenate more than one string and build a new string out of those strings.
Following is an example:

let myName = "My name is " + 'Swarnali Roy. ' + "I am an Engineer.";
console.log(myName);

//op: My name is Swarnali Roy. I am an Engineer.
Enter fullscreen mode Exit fullscreen mode

🔹 We can also use the * += operator * to concatenate a string onto the end of an existing string variable. This can be very helpful for breaking a long string over several lines. For example:

let myName = "My name is Swarnali Roy ";

myName += "and I am a Software Engineer.";
console.log(myName);

//output: My name is Swarnali Roy and I am a Software Engineer.
Enter fullscreen mode Exit fullscreen mode

🔹 By using the concatenation operator, we can also insert one or more variables into a string that we want to build. A simple example is given below:

let myName = "Swarnali Roy ";
let passion = "to code."

let myStr = "My name is " + myName + "and I love " + passion + "."

console.log(myStr);

//output: My name is Swarnali Roy and I love to code.
Enter fullscreen mode Exit fullscreen mode

🔹 We can also append variables to a string using the plus equals (+=) operator.

let nameStr = "I am ";
let myName = "Swarnali ";
let passion = "and I love programming."

let str = nameStr += myName += passion;

console.log(str); //op: I am Swarnali and I love programming.
Enter fullscreen mode Exit fullscreen mode
An important thing to notice is, concatenation does not add spaces between concatenated strings, so we'll need to add them ourselves.

To make the process compact, JavaScript ES6 has introduced Template Literals. They were called "Template Strings" in prior editions of the ES2015 specification.

🔶 Creating Strings using Template Literals

🔹 Template literals allow us to create multi-line strings and to use string interpolation features to create
strings.
🔹 Generally if we want to solve any problem with normal string manipulation, we need to concatenate the value with the string with + operator as we have seen till now. But template literals make it simpler and remove the complications of using single or *double quotes, backslashes and concatenation operators.

The basic syntax is:

`string text ${expression/variable} string text`;
Enter fullscreen mode Exit fullscreen mode

Let's see an example of Template Literals below and then get into the explanation.

let weather = "cloudy";
let myFav = "when it rains"

let myStr = `Today's weather is ${weather}.
I love ${myFav}.`

console.log(myStr);

/* Today's weather is cloudy.
I love when it rains. /
Enter fullscreen mode Exit fullscreen mode

If we see the example, a lot of things can be noticed.

🔹 First of all, back-ticks are used to wrap the string, not quotes (' or ").
🔹 Secondly, it is a multi-line string, both in the code and the output. This saves inserting newline ( \n ) within strings.
🔹 The ${variable} syntax used in the example is a basically a placeholder. So we don't need to concatenate the variables with the + operator anymore. We can simply put the variable in a template literal and wrap it with ${ }, to add it to strings.
🔹 Also, we can include other expressions, for example ${a + b} directly to the template literal.

Hence, this process of building strings gives us more flexibility to create robust and complex strings.

Immutability of Strings

In JavaScript, string values are immutable, which means that they cannot be changed once they're created. At first, let's create a string.

let animal = "Cat";
animal[0] = "B";

console.log(animal); //output : Cat
Enter fullscreen mode Exit fullscreen mode

We cannot change the value of animal to Bat, using bracket notation [ ], because the contents of the string cannot be altered by changing the value of their indices. The individual characters of a string literal cannot be changed.

However, we can still change the string value of animal to Bat. The only way to change it would be to assign it with a new string value, like this:

let animal = "Cat";
animal = "Bat";

console.log(animal); //output : Bat
Enter fullscreen mode Exit fullscreen mode

At last, I have some problems for my readers to solve. You can answer them in the discussion section. Any kind of questions are always welcome.

1️⃣ Assign the following lines of text into a single variable using escape sequences. Expected output:

Today is Sunday.
    \Tomorrow is Monday\
What was yesterday?
Enter fullscreen mode Exit fullscreen mode

2️⃣ Correct the code using backslash.
Expected output: Anna said, "let's go on a trip."

let str = "Anna said, " let's go on a trip.";
console.log(str);

//output: SyntaxError: Unexpected identifier
Enter fullscreen mode Exit fullscreen mode

3️⃣ Using "Template Literals" change the following code. The output will be the same.

let realName = "Robert Pattinson ";
let reelName = "Edward Cullen ";
let movieName = "Twilight";

let fullStr =
  realName + "played the role of " + reelName + "in the movie " + movieName;

console.log(fullStr);

//output: Robert Pattinson played the role of Edward Cullen in the movie Twilight.
Enter fullscreen mode Exit fullscreen mode

Discussion (5)

Collapse
akashsarkar profile image
Akash Sarkar

I learned something new about string immutability

Collapse
peerreynders profile image
peerreynders

MDN: Primitive

All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.

Collapse
swarnaliroy94 profile image
Swarnali Roy Author

Glad to know that. 😌

Collapse
auniik profile image
Auniik Datta

Great.

Collapse
swarnaliroy94 profile image
Swarnali Roy Author

Thanks