JavaScript Strings

In this section of the tutorial, we will discuss Strings in JavaScript and their uses to assign a variable with no character or one character or a combination of characters inside a single or double quote.

What are Strings in JavaScript?

In JavaScript, Strings are the set or combination of one or more characters of text. We instruct the JavaScript engine to treat the Strings as text and not as a code by closing the Strings in single or double quotes.

Example:

“C” and “CODEDEC” are both treated as Strings. ” ” is also treated as Strings even if there is not any character inside the quotes.

We will take a code example to understand the behavior of Strings in JavaScript.

Code:

  • Here, variable a, b, and c are assigned String values in them.
  • We can clearly see that the String values are closed in double quotes.
  • In the terminal, we can see the output where the console.log() displays the values as Strings.
  • This proves that JavaScript is recognizing the values as Strings.

Working with Strings

In JavaScript, we can manipulate Strings to meet our requirements in the code. There are several built-in features in JavaScript that can perform different operations on Strings.

Example:

Concatenation of strings is one of the built-in features in JavaScript that joins two or more strings together. This can be achieved using the Addition operator + which we have discussed in JavaScript Operators.

Code:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

var TestVariable;

TestVariable = "WELCOME TO CODEDEC";

document.write(TestVariable);

</script>
</head>
<body>
</body>
</html>

Output:

WELCOME TO CODEDEC
  • Here, we first declared the variable TestVariable using the keyword var.
  • Then, we assigned a String using the assignment operator =.
  • We stored a string value in the variable.
  • Then we accessed the values inside the variable and using the document.write() method, the message is displayed.

We can also determine the length of a string using the property of the string: s.length

Similarly, there are many Properties in JavaScript that enable us to play with strings.

Example:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

var s = "Hello, world";

</script>
</head>
<body>
</body>
</html>

Now, we will understand some Properties of JavaScript in reference to code written in the above example.

Accessing portion of a String
s.substring(1,4) “ell”: the 2nd, 3rd, and 4th characters
s.slice(1,4) “ell”: the 2nd, 3rd, and 4th characters
s.slice(-3) “rld”: last 3 characters
s.split(“, ”) [“Hello”, “world”]: split at delimiter string
Searching a String
s.indexOf(“l”) 2: position of first letter l
s.indexOd(“l”, 3) 3: position of first “l” at or after 3
s.indexOf(“zz”) -1: s does not include the substring “zz”
s.lastIndexOf(“l”) 10: position of last letter l
Boolean search in ES6 and later
s.startWith(“Hello”) true: the string starts with these
s.endsWith(“!”) false: s does not end with that
s.includes(“or”) true: s includes substring “or”
Modifying a String
s.replace(“llo”, “y”) “Hey, world”
s.toLowerCase() “hello, world”
s.toUpperCase() “HELLO, WORLD”
s.normalize() Unicode NFC normalization
s.normalize(“NFD”) NFD normalization. Also “NFKC”, “NFKD”
Inspecting individual character of a String
s.charAt(0) “H”: the first character
s.charAt(s.length-1) “d”: the last character
s.charCodeAt(0) 72: 16-bit number at specified position
s.codePointAt(0) 72: works for codepoints
String padding
“x”.padStart(3) “ x”: add spaces on the left to a length of 3
“x”.padEnd(3) “x ”: add spaces on the right to a length of 3
“x”.padStart(3, “*”) “**x”: add stars on the left to a length of 3
“x”.padEnd(3, “-”) “X–”: add dashes on the right to a length of 3
Space trimming
“ test ”.trim() “test”: remove spaces at start and end
“ test ”.trimStart() “test ”: remove spaces on left (Also use trimLeft)
“ test ”.trimEnd() “ test”: remove spaces on right (Also use trimRight)
Other String function
s.concat(“!”) “Hello, world!”: (Also use + operator to do the same)
“<>”.repeat(5) “<><><><><>”: concatenate n copies

Strings can also be used as read-only arrays for accessing individual characters from a String using square brackets ‘[ ]’ instead of charAt() method.

Example:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

var a = "hello, world";
a[4] // => "o"
a[a.length-3] // => "r"

</script>
</head>
<body>
</body>
</html>

Now that we are familiar with many built-in features in JavaScript to manipulate and access Strings. Let’s discuss some basic operations we can carry out on Strings.

Basic String Operations

In JavaScript, we can manipulate Strings using operators which we have learned in detail in JavaScript Operators. We have already discussed a property called Concatenation above, that joins one or more strings together and this feature is most commonly used in JavaScript.

Let’s discuss two more ways to manipulate Strings in JavaScript, i.e. Mixing numbers and strings and comparing strings.

Mixing Numbers and Strings

In JavaScript, if a user wants to mix numbers and text together, then this can be easily done using the Addition + operator. It is in the intelligence of JavaScript that automatically senses if there is any numerical value in the input along with the text. No calculations are performed in such a case, only the numbers are joined together with the string value.

Example:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

document.write("WELCOME TO THE YEAR "+ 2021);

</script>
</head>
<body>
</body>
</html>

Output:

WELCOME TO THE YEAR 2021
  • We can clearly see that the combination of String value and Number value is displayed in the output.

Comparing Strings

In JavaScript, if a user wants to do a comparison between two or more String values just like it is done with numbers using comparison operators. Then this can be achieved using the same comparison operators for comparing strings too.

Comparison of Strings is done in the same way that we compare numbers but with only one major difference, i.e. keeping in mind that the String value will be compared alphabetically rather numerically.

Example:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

var name ="Tom";

if (name == "Tom")
{
 document.write(“name is Tom”);
}



</script>
</head>
<body>
</body>
</html>
  • Here, the comparison is done by checking each letter in turn on the LHS and checks it with the letter in the same position on the RHS.
  • If at any position, any character is found unmatched, the comparison stops and the result is false.
  • If all the positions on both LHS and RHS have the same characters, then the result is true, and the flow control will enter the braces and execute the document.write() function.

Escape Sequences in String

In JavaScript, it is common to face a situation where we need to include an apostrophe in a String value that is closed in single or double quotes. Without it, there can be confusion and hence an error in recognizing the correct String value.

Example:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

document.write('I'm Tom and He's Jerry.');

</script>
</head>
<body>
</body>
</html>
  • Here, the String value inside the document.write() function is closed under single quotes, which is a valid way to write a String in JavaScript.
  • But, we have also included apostrophe at I’m and He’s, here the function will throw an error or print the wrong string value.

Example:

<html>
<head>
<title>Variable Examples</title>
<script type="text/javascript">

document.write('I\'m Tom and He\'s Jerry.');

</script>
</head>
<body>
</body>
</html>
  • Here, the String value inside the document.write() function is closed under single quotes, which is a valid way to write a String in JavaScript.
  • And also we have included a backslash character(\) before the apostrophe at I\’m and He\’s, here the function will display the correct string value, i.e. I’m Tom and He’s Jerry.

Similarly like we have used a backslash character (\) in the above example to ignore the apostrophe, we can also use many other different Escape Sequences to avoid any error in the output of the String values.

Below is a table that briefly lists some escape sequences and the character they represent.

Escape Sequences

Character Represented

\b

Used for Backspace

\f

Used for Form Feed
\n

Used for New Line

\r

Used for Carriage Return
\t

Used for Tab

\’

Used for Single Quote
\”

Used for Double Quote

\\

Used for Backslash
\xNN

NN is a hexadecimal number that specifies a character in Latin-1 character set

In the next section of the tutorial, we will discuss Arrays in JavaScript and their uses to store multiple values in a single variable and performing different operations on it.