String Manipulation in JavaScript
Tags: javascript, codenewbie, tutorial, beginners
Published: 2021-08-10 17:34:51

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

```js
let myName = 'My name is Swarnali Roy'
```
or,
```js
let myName = "My name is Swarnali Roy"
```
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*.

###:large_orange_diamond: 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.

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

```js
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 */
```
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 "". 

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

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

//output: She said, ' My name is Swarnali Roy '.
```
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.

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

//output: She said, " My name is Swarnali Roy ".
```
Now, the backslash is separating the literal quote and the quote is appearing inside the string. 

###:large_orange_diamond: 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:

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

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

A simple example is :point_down:  

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

/* output: She said,
	           'My name is
           Swarnali Roy'. */
```

###:large_orange_diamond: Concatenating Strings with + Operator

:small_blue_diamond: 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*: 
```js
let myName = "My name is " + 'Swarnali Roy. ' + "I am an Engineer.";
console.log(myName);

//op: My name is Swarnali Roy. I am an Engineer.
```
:small_blue_diamond: 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*:

```js
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.
```
:small_blue_diamond: 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:

```js
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.
```
:small_blue_diamond: We can also *append variables* to a string using the *plus equals (+=)* operator.

```js
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.
```

###### 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.

###:large_orange_diamond: Creating Strings using Template Literals

:small_blue_diamond: Template literals allow us to create multi-line strings and to use *string interpolation* features to create 
strings.
:small_blue_diamond: 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:
```js
`string text ${expression/variable} string text`;
``` 
Let's see an *example* of *Template Literals* below and then get into the explanation. 

```js
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. /
```

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

:small_blue_diamond: First of all, *back-ticks* are used to wrap the string, not *quotes (' or ")*.
:small_blue_diamond: Secondly, it is a *multi-line string*, both in the code and the output. This saves inserting *newline ( \n )* within strings.
:small_blue_diamond: 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. 
:small_blue_diamond: 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.

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

console.log(animal); //output : Cat
```

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:

```js
let animal = "Cat";
animal = "Bat";

console.log(animal); //output : Bat
```
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. 

:one: Assign the following lines of text into a *single variable* using *escape sequences*. Expected output:

```js
Today is Sunday.
    \Tomorrow is Monday\
What was yesterday?
```
:two: Correct the code using backslash. 
Expected output: Anna said, "let's go on a trip."

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

//output: SyntaxError: Unexpected identifier
```
:three: Using "Template Literals" change the following code. The output will be the same.

```js
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.
```