DEV Community

Cover image for JavaScript: How to make the most out of Strings ?
The daily developer
The daily developer

Posted on

JavaScript: How to make the most out of Strings ?

Strings are a primitive data type that represent a series of characters. A string's syntax allows you to create a string that includes letters, spaces, symbols and numbers.

In this article we'll cover:

  1. Strings Syntax
  2. Escape characters
  3. String Concatenation
  4. Strings are immutable
  5. String Methods

Strings Syntax

Strings are as we said, a series of characters that include letters, spaces, symbols and numbers wrapped within single, double quotes or backticks which is known as template literals.

let singleQuotes = 'This is a string with single quotes.';
let doubleQuotes = "This is a string with double quotes.";
Enter fullscreen mode Exit fullscreen mode

A double quoted string can contain single quotes like so:

let sentence = "I'm named 'John'".
console.log(sentence) // I'm named 'John'
Enter fullscreen mode Exit fullscreen mode

Template literals are a feature of ES6. They make it possible to include variables and expressions inside a string.

let backticks = `This is a string with backticks.`;
//or
let name = "John";
let age = 22;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // Output: Hello, my name is John and I am 22 years old.
Enter fullscreen mode Exit fullscreen mode

Escape Characters

To represent characters that are special or can be tricky to include in a string or code, in this case escape characters are used. When escape characters are used they tell the interpreter how it should treat the next character.

Escape Sequence Meaning
\n goes to a new line
\t gives you a tab space
\" escapes double quotes
\' escapes single quotes
\ escapes a backslash

Let's look at some examples:

// \n
let newLine = "I am the first line.\nI am the second line.";
console.log(newLine);
/*
I am the first line.
I am the second line.
*/

// \t
let indentation = "One\tTwo\tThree";
console.log(indentation); // One   Two  Three

// \"
let quoteEsc = "Hi, I am \"John!\"";
console.log(quoteEsc); //  Hi, I am "John!"

// \'
let singleEsc = "I\'m Happy";
console.log(singleEsc); // I'm Happy

// \`
let message = `She said, \` I am at the beach.\``;
console.log(message); // Output: She said, ` I am at the beach`.
Enter fullscreen mode Exit fullscreen mode

String Concatenation

String concatenation means combining multiple strings together to form a longer string. This can be done using the + operator or using concat() which we'll discuss later in this article.

let firstName = "Jane";
let lastName = "Doe";
console.log(firstName + " " + lastName); 
// Jane Doe
Enter fullscreen mode Exit fullscreen mode

As we've previously mentioned, template literals allow us to include variables in our strings so we can concatenate using the same syntax.

let firstName = "Jane";
let lastName = "Doe";

console.log(`${firstName} ${lastName}`); // Jane Doe
Enter fullscreen mode Exit fullscreen mode

Strings Are immutable

When a String is created, it cannot be changed. This means when you alter your string for example by using concatenation, you create a new string that holds the content that was modified leaving the original string unchanged.

To further understand this concept let's take a look at what bracket notation is. Bracket notation is used to access a string's characters (and arrays which we'll get to later in this series). Let's use the example "I am Tom" to see how this works. Let's say we want to know where the letter "m" in Tom is located within that string. The position of “m” is known as an index, and indices are counted starting at zero which is known as (zero-based indexing). Count the spaces too

The "m" in Tom is found at index 7. The syntax to access it is as follows:

let str = "I am Tom";
console.log(str[7]);// m
Enter fullscreen mode Exit fullscreen mode

Let's take a look at this example:

let str= "I am Tob";
str[7]= "m";
console.log(str); // I am Tob
Enter fullscreen mode Exit fullscreen mode

In this example, I've misspelled Tom. Using this bracket notation to fix the misspelling will not work. The output will still be I am Tob.

You can fix this issue by reassigning the variable string giving it the value of I am Tom.

let str= "I am Tob";
str = "I am Tom"
console.log(str); // I am Tom
Enter fullscreen mode Exit fullscreen mode

String Methods

Now that we've covered the basics of strings, let's see how to modify, transform and extract data from strings.

String manipulation

Manipulating strings is the act of changing or modifying a string. This process is done through the string manipulation methods.

String Manipulation Description
length This method returns the character count or length of a string.
replace() This method replaces the first occurrence of value you've specified with another in a string.
replaceAll() This method replaces all the occurrences of the same value you've specified with another in a string.
toUpperCase() This method returns a new string of uppercase characters. The original string is not modified.
toLowerCase() This method returns a new string of lowecase characters. The original string is not modified.
concat() This method is used to concatenate multiple strings. It returns a new string without modifying the original string.
trim() This method removes white spaces from the start and end of the string
trimStart() This method removes white spaces from the start of the string.
trimEnd() This method removes white spaces from the end of the string.
padStart() This method is used to add specific characters at the start of the string.
padEnd() This method is used to add specified characters at the end of the string.
  • Length
 let str = "123456abcdef";
 console.log(str.length); // 12
Enter fullscreen mode Exit fullscreen mode
  • replace()
let str = "Read my blog!";
let newStr = str.replace("blog", "articles");
console.log(newStr); //Read my articles!
Enter fullscreen mode Exit fullscreen mode

It's important to remember that the replace() method doesn't change the original string. The first match is replaced, and a new string is returned.

let str = "Read my blog!";
console.log(str.replace("blog", "articles")); //Read my articles!
console.log(str); //Read my blog!
Enter fullscreen mode Exit fullscreen mode

It is also case-sensitive and will not replace your input if one is in lowercase and the other in uppercase.

let str = "Hi, Hi, Hi!";
let newStr = str.replace("hi", "Bye");
console.log(newStr);// Hi, Hi, Hi!
Enter fullscreen mode Exit fullscreen mode
  • replaceAll()
let str = "Hi, Hi, Hi!";
let newStr = str.replaceAll("Hi", "Bye");
console.log(newStr); // Bye, Bye, Bye!
Enter fullscreen mode Exit fullscreen mode

Keep in mind that the replaceAll method works the same as the replace() method. The only difference is that it replaces all the occurrences of a value you've given it with another as we mentioned above.

  • toUpperCase()
let str = "hello reader!";
console.log(str.toUpperCase()); //HELLO READER!
Enter fullscreen mode Exit fullscreen mode

-toLowerCase()

let str = "Hello Reader!"
console.log(str.toLowerCase()); //hello reader!
Enter fullscreen mode Exit fullscreen mode
  • concat()

We've previously used the + operator to concatenate multiple strings. The concat() method can do the same thing.

let str1 = "Hello";
let str2 = "Reader!"
let str3 = str1.concat(" ", str2);
console.log(str3);// Hello Reader!

// concatenating 3 strings
let str1 = "Hello";
let str2 = "Reader"
let str3 = "!"
let str4 = str1.concat(" ", str2, str3);
console.log(str4); // Hello Reader!
Enter fullscreen mode Exit fullscreen mode
  • trim()
let str = "   Hello Readers!   ";
console.log(str.trim()); //Hello Readers!
Enter fullscreen mode Exit fullscreen mode
  • trimStart()
let str = "   Hello Readers!";
console.log(str.trimStart()); //Hello Readers!
Enter fullscreen mode Exit fullscreen mode
  • trimEnd()
let str = "Hello Readers!   ";
console.log(str.trim()); //Hello Readers!
Enter fullscreen mode Exit fullscreen mode
  • padStart()

The padStart() method takes two arguments. The first defines how long we want out string to be. The second is the character we want to use.

let str = "26";
console.log(str.padStart(5, "0")); // 00026
Enter fullscreen mode Exit fullscreen mode

In our example we've said that, " i want my string to have a length of 5 and use 0 to pad the beginning".

  • padEnd()

This method works the same way as padStart() but instead of padding the beginning it is done at the end.

let str = "26";
console.log(str.padEnd(5, "0")); // 26000
Enter fullscreen mode Exit fullscreen mode

String extraction

String Extraction Description
slice() This method extracts a portion of a string based on indices passed as arguments.
substring() This method is similar to slice the only difference is that any negative number passed as an argument will be considered 0.
substr() This method returns a segment of the string's beginning at the given index and continuing for the number of characters that you specify.
charAt() This method gives back the character at the index you passed as argument.
charCodeAt() This method gives back the unicode of the character at the index you passed as argument.
split() This method converts a string into an array.
  • slice()

slice() creates a new string by taking a section of an existing string. This method requires two arguments: the start position, which is inclusive (takes into account the starting position), and the end position, which is Exclusive (does not take into account the ending position).
Keep in mind zero-based indexing.

let str = "Slice this string";
let strSlice = str.slice(11,17);
console.log(str);
console.log(strSlice);
/*
Slice this string
string
*/
Enter fullscreen mode Exit fullscreen mode

If the second parameter is omitted, the method will remove the remainder of the string.

let str = "Slice this string";
let strSlice = str.slice(6);
console.log(str);
console.log(strSlice);
/*
Slice this string
this string
*/
Enter fullscreen mode Exit fullscreen mode

-substring()
slice() and substring() are similar methods. the only difference is that any negative number passed as an argument will be treated as 0. Similar to slice(), substring() will slice off the rest of the string if a second argument is not provided.

let str = "Slice this string";
let strSubstring = str.substring(-3, 4);
console.log(str);
console.log(strSubstring); //Slic
Enter fullscreen mode Exit fullscreen mode
  • substr()

This method is similar to substring() the only difference is that it can handle negative indices. It is able to use negative indices as a starting point from the end of the string.

let str = "Slice this string";
let strSubstr = str.substr(-3, 4);
console.log(str); //Slice this string
console.log(strSubstr); // ing
Enter fullscreen mode Exit fullscreen mode
  • charAt()
let str = "hi";
let char = str.charAt(0);
console.log(char); //h
Enter fullscreen mode Exit fullscreen mode
  • charCodeAt()

Simply put, Unicode is a system that assigns each character from every language a unique value or code. This is done to ensure that computers can recognize letters and symbols and numbers correctly. This allows the text to be uniform across all platforms. For more information visit About the Unicode Consortium

let str = "hi";
let char = str.charCodeAt(0); 
console.log(char); // 104
Enter fullscreen mode Exit fullscreen mode
  • split()

This method takes a separator as argument. the separator could be a space, comma or anything else you'd like. The split() method splits the string each time it encounters the separator you've specified.

let str = "Hello, how are you today?";
console.log(str.split(" ")) 
//[ 'Hello,', 'how', 'are', 'you', 'today?' ]

Enter fullscreen mode Exit fullscreen mode
let str = "Hello, how are you today?";

console.log(str.split(","));
[ 'Hello', ' how are you today?' ]

Enter fullscreen mode Exit fullscreen mode

String search methods

The string search methods are case-sensitive.

Method Description
indexOf() This method gives back the index of the first occurrence of the string passed as argument
lastIndexOf() This method gives back the index of the last occurrence of the string passed as argument
search() This method is the same as the indexOf method but it cannot take a starting position as a second argument.
match() This method uses a regular expression to search for the pattern passed as argument and return the first occurrence.
matchAll() This method is the same as match but returns all the occurrences that match the pattern passed as argument.
includes() This method returns a boolean value (true or false). if a string contains the value passed as argument it returns true.
startsWith() This method returns a boolean value. If a string starts with the value passed as argument it returns true.
endsWith() This method returns a boolean value. If a string ends with the value passed as argument it returns true.
  • indexOf()
let str = "Hello, Reader!"
console.log(str.indexOf("a")); //9
Enter fullscreen mode Exit fullscreen mode
  • lastIndexOf()
let str = "Hello, Reader!"
console.log(str.lastIndexOf("e")); //11
Enter fullscreen mode Exit fullscreen mode

Both indexOf and lastIndexOf return -1 if the argument passed was not found and can accept another argument as the starting position for searching.

  • search()

This method can be used with regular expressions which we'll be seeing later on in this series.

  • includes()
let str = "Hi, Reader!";
console.log(str.includes("Hi")); // true
Enter fullscreen mode Exit fullscreen mode
  • startsWith()
let str = "See you later";
console.log(str.startsWith("See")); //true
Enter fullscreen mode Exit fullscreen mode
  • endsWith()
let str = "See you later";
console.log(str.startsWith("See")); //false
console.log(str.endsWith("later")); //true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)