Table of contents
1.
Introduction
2.
Immutability
3.
Quotes
4.
String length
5.
Accessing characters
6.
Changing case
7.
Getting substrings
8.
Searching for substrings
9.
Comparing strings
10.
Special characters
11.
Frequently Asked Questions
12.
Key takeaways
Last Updated: Mar 27, 2024

JS Strings

Author Reet Maggo
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Characters or sequences of characters in JavaScript are stored as strings. Strings are either used to represent or manipulate data in JavaScript. A JavaScript string can have either 0 or more characters within the quotes. There are three kinds of quotes for strings, various special characters to use within those quotes and several functions to manipulate, operate on, or retrieve strings or substrings. This article will discuss the common operations on strings, along with illustrative and suitable examples.

See, Javascript hasOwnProperty

Immutability

In Javascript, strings are immutable, i.e., the characters cannot be changed in Js. 

Example:

let str = 'Name';
str[0] = 'n'; // will show an error
alert( str[0] ); // will not work
You can also try this code with Online Javascript Compiler
Run Code

 

This shows that we cannot alter the string once it is generated. To do so, we must create a new string and concatenate the previous one onto it as shown below. 

let str = 'Name';
str = 'n' + str[1]; // replacing the old string with the new one
alert( str ); // name
You can also try this code with Online Javascript Compiler
Run Code

Quotes

There are three kinds of quotes in Javascript:

  • single quotes
  • double quotes
  • backticks

For examples:

let single='hello' // single quotes
let double=''hello'' // double quotes
You can also try this code with Online Javascript Compiler
Run Code

 

There is no effective difference between single and double quotes, but it is recommended that we stick to using one of them throughout the code to enhance the readability. However, there is a new way of writing strings: template literals

let backticks=`Hello`
You can also try this code with Online Javascript Compiler
Run Code

 

Template literals use backticks to easily build dynamic strings. Backticks are much more versatile than both single and double-quotes. They allow multiline strings and also embed expressions into the string (by wrapping in ${…}.

For example:

Multline strings:

let employees= `Employee:
* Ryan
* Chris
* Anne
`;
alert(employees);
// multiline strings
You can also try this code with Online Javascript Compiler
Run Code

 

Embedding expressions in string:

function sum(x, y)
{
  return x + y;
}

alert(`10 + 90 = ${sum(10, 90)}.`);  // 10 + 90 = 100
// Embedding expressions by wrapping in ${...}
You can also try this code with Online Javascript Compiler
Run Code

String length

To find the string length, we use .length property which gives an integer output.

For example: 

alert( `Coding Ninjas`.length ); // 13
You can also try this code with Online Javascript Compiler
Run Code

 

The .length property is often confused with the length() method which is used in many programming languages. But it is worth noting that both are distinct in nature. 

Now let us see how one can access the characters of a string:

Accessing characters

To get a character at a particular position, we can either specify it using square brackets [position] or by calling the method string.charAt(position). The first position is always zero. Therefore, the last character is one less than the length.

let str1 = `Name`;

alert( str1[0] ); // the first character is N
alert( str1.charAt(0) ); //the first character is N

alert( str1[str1.length - 1] ); //the last character is e
You can also try this code with Online Javascript Compiler
Run Code

 

Characters can be iterated using for..of. 

for (let char of "Name")
{
  alert(char); // N,a,m,e: char will first be "N", then "a", then "m", and finally "e".
}
You can also try this code with Online Javascript Compiler
Run Code

 

For characters not found:

Square brackets returns undefined when no character is found, while charAt just returns an empty string. 

Example1

let str1 = `Name`;

alert( str1[10] ); 

Output undefined
Example 2 alert( str1.charAt(10) );
Output '' (empty string)

 

 

 

 

 

 

 

Also check out - Substr C++

Changing case

The methods used for changing case are simply toUpperCase() and toLowerCase().

For examples:

alert( 'Bolivia'.toUpperCase() ); // changes Bolivia to BOLIVIA
alert( 'Bolivia'.toLowerCase() ); // changes Bolivia to bolivia
alert( 'Bolivia'[0].toLowerCase() ); // changes the 0th character to 'b'
You can also try this code with Online Javascript Compiler
Run Code

Getting substrings

Substrings are sub-parts within the given string, either a fragment of the string or the complete string itself. To attain substrings, we can use slice, substring or substr.

Let us look at them one by one:

slice

It is written as string.slice(start, end), where start is the starting index and the second argument(specifying the end) is optional.

If the end is mentioned too, slice returns the substring from the given starting index until before the end(not the end). 

For examples:

let str = "Paris";
alertstr.slice(04) ); // returns 'Pari' starting from 0, excluding 4


alertstr.slice(01) ); // returns 'P' starting from 0, excluding 1


alertstr.slice(2) ); // No end position specified. Returns 'ris', from the 2nd position till the end

We can also pass negative indexes for start and end, where the position will be calculated with the help of string’s length. 

For example:

alertstr.slice(-3-1) ); // returns 'ris'

The above example has -3 in the starting index and it will be calculated as:  

  start: length + (Negative index) // 5 + (-3) = 2

  end: length + (Negative index) // 5 + (-1) = 4 

substring

This works similar to slice, but the start and end positions can be interchanged.

let str = "Hello";
alert( str.substring(1, 4) ); // returns "ell"
alert( str.substring(4, 1) ); // returns "ell"
You can also try this code with Online Javascript Compiler
Run Code

 

If the starting and ending positions are interchanged, the slice returns an empty string. However, unlike slice, substring does not support negative arguments and treats them as 0.

substr

It is pretty similar to string.slice(start, length), only one change has to perform that instead of specifying the end position, users need to specify the substring length. Substr accepts negative values for start argument, while the length always has to be positive.

let str = "Hamilton";
alert( str.substr(0, 3) ); // 'Ham', 3 characters starting from the 1st position
alert( str.substr(-6, 4) ); // 'mil', 4 characters starting from the 6th position backwards
You can also try this code with Online Javascript Compiler
Run Code

Searching for substrings

Substrings can be searched using several methods:

str.indexOf

This searches within the string for the given substring starting from a given position. It will either return the position where the match is found or return -1 if it isn’t found.

It is case sensitive, and the syntax for this is str.indexOf(substring). We can also have an optional position parameter like:  str.indexOf(substring, position). 

let str'Chris from Paris';
alertstr.indexOf('Chris') ); // the position returned will be 0



 

alertstr.indexOf('Paris') ); // the position returned will be 11



 

alertstr.indexOf('Par') ); // the position returned will be 11


alertstr.indexOf('is') ); // the position returned will be 3 because that's the first occurrence of the given substring

alertstr.indexOf('london') ); // returns -1, as it is case-sensitive

alertstr.indexOf('is', 4) ); // the first occurrence of 'is' is 3. Therefore we'll start searching from index 4. Returns 14.

bitwise NOT trick

This converts numbers to 32 digit integers, removing their decimal parts, and reverses all bits in binary representation.~n equals -(n+1).

~2 returns -3, which is equal to -(2+1)

~0 returns -1, which is equal to -(0+1)

~-1 returns 0, which is equal to -(-1+1)

Therefore, ~n zero only for n == -1 (for 32-bit signed integer n).

Now, if (~str.indexOf(...)) reads as “if found”, and to shorten indexOf checks:

let str = "Paris";
if (~str.indexOf("Paris"))
{
  alert( 'Found it!' ); // works
}
You can also try this code with Online Javascript Compiler
Run Code

 

Moving on to the more efficient and modern way for the same purpose:

includes, startsWith, endsWith

All three of these functions return true or false for the substring being found in the given string. We could just use .includes(string), or specify the position to start searching from as in .includes(string, position).

alert( "Chris in Paris".includes("Chris") ); // returns true
alert( "Chris in Paris".includes("chris") ); // returns false because it is case sensitive

alert( "Chris in Paris".includes("Chris", 7) ); // returns false because there is no “Chris” after position 7

.startsWith(string) and .endsWith(string) are the syntaxes for functions that check the beginning and end of a string for the substring, respectively.

alert( "Chris in Paris".startsWith("Chr") ); // returns true
alert( "Chris".endsWith("is") ); // returns true
You can also try this code with Online Javascript Compiler
Run Code

Comparing strings

The following are some important points we must remember for comparison between strings:

  • There is a character-by-character comparison between two strings.
  • Lowercase strings are greater than uppercase strings.
  • Diacritical marks on characters (á, é, ó, ü, ñ) in strings often cause unexpected results.
  • Both upper and lower-case characters in strings have specific numeric codes or ASCII codes. (Starting from 065 for uppercase alphabets and 097 for lowercase alphabets. Therefore a>A, h>H, etc)

 

alert( 'c' > 'G' ); // returns true
You can also try this code with Online Javascript Compiler
Run Code

 

str.codePointAt(pos)

This takes the position as string.codePointAt(position), and returns the ASCII code for the character at the given position:

alert( "apple".codePointAt(0) ); // returns 97 because lowercase a has code 97
alert( "Apple".codePointAt(0) ); // returns 65 because uppercase A has code 65
You can also try this code with Online Javascript Compiler
Run Code

 

String.fromCodePoint(code)

This lets us give a numeric code and generate the corresponding character for it.

alert( String.fromCodePoint(68) ); // D
You can also try this code with Online Javascript Compiler
Run Code

 

Similarly, instead of giving ASCII codes, we can also give Unicode characters by using \u followed by the hex code:

alert( '\u005a' ); // in the hexadecimal system, 90(uppercase Z) is 5a
You can also try this code with Online Javascript Compiler
Run Code

Special characters

Special characters, always known as escape characters and escape sequences always begin with a backslash'/'.  Escape sequences are character sequences inserted in a string to have a meaning different from the literal characters.

Some common special characters in JavaScript include:

\n Newline
\', \" Quotes
\\ Backslash
\t Tab
\b, \f, \v Backspace, Form Feed, Vertical Tab – kept for compatibility, not used nowadays.
\r Carriage return

We can create multiline strings even without backticks, with single and double quotes by using the newline character-\n, denoting a line break:

let string1 = "Chris\nAnne"; // two lines using a "newline symbol"
let string2= `Chris
Anne`;
alert(string1 == string2); // true
You can also try this code with Online Javascript Compiler
Run Code

 

let string1 = "Hello\tAnne"; // using tabspace
let string2= `Chris     Anne`;
alert(string1 == string2); // true
You can also try this code with Online Javascript Compiler
Run Code

You can practice by yourself on an online JS editor.

Frequently Asked Questions

Q1. How can we remove leading and trailing spaces in a string? 

Ans. The .trim() method helps us remove extra spaces both at the beginning and the end of a string in JavaScript.

Q2. What are the three methods of getting substrings from Js Strings?

Ans. We can use either of the three: .slice(start,end), .substring(start,end) or substr(start, length) to get case-sensitive substrings in JavaScript.

Q3. How can we join two or more strings in JavaScript?

Ans. The .concat() method helps join two or more strings. The syntax for this method can be: str1.concat(" ", str2)

let string1"Hey";
let string2"students!";
let string3"Great to see you!";
let resultstring1.concat(" "string2" "string3);

Q4. What is the repeat method used in Javascript?

Ans. The .repeat() method repeats the string n number of times. Its syntax is str.repeat(n) – where ‘str’ is the string and ‘n’ is the number of times a user wants the string repeated.

Key takeaways

In this article, we learned about the operations we can perform on strings includes searching and retrieving substrings, comparing two strings and many more. We have extensively used examples to illustrates the concept and better clarification the situations where each kind of method could be applied.

Check out this article - String slicing in Python

Recommended problems -

 

You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.

Live masterclass