JavaScript (ES6) — String and String Methods

Raj
The Dev Guide
6 min readNov 6, 2019

--

Photo by Nate Grant on Unsplash

In Javascript, text-based data is stored in String i.e Javascript strings are used to store and handle texts. There is no separate type for storing Single Character.

A Javascript String is anything written inside the Quotes.

For Example —

let message = 'Hey There! How are you?';

In Javascript, you can use Single Quotes as well as Double Quotes for Strings.

let sentMessage = 'Hey! How are you?';    // Single quote
let receivedMessage = "Hey! I am Fine."; // Double quotes

You can also use quotes inside the string as long as they do not match the quotes surrounding the string.

let message = "Hey There! My name is 'John Doe'. I am a Software Developer.";

You can also use “Backtick”, an ES6 feature to declare a string.

let message = `Hey There! I am using Medium`;

Backticks, allow us to embed any expression into the string, by wrapping it in ${…}.

let firstName = "John";
let lastName = "Doe";
let message = `Hello ${firstName} ${lastName}`;
console.log(message) // "Hello John Doe"

You can also call a function inside the Backtick string.

function sum(a,b){
return a + b;
};
console.log(`5 + 5 is ${sum(5,5)}`) // 5 + 5 is 10

Another advantage of backtick is they allow the string to span in multiple lines.

let friends = `Friend List : 
John Doe,
Mick Ross,
Donna Paulsen`;

Backticks String is the same as Single or Double Quotes String with some more advantages. I would Ideally recommend you to use Backticks more often than traditional string as they have better advantages and we can easily write Human-readable String with Expressions and Variables.

String Methods

Primitive Values, cannot have properties or methods because they are not Objects.

But in JavaScript, Primitive Values are treated as Objects when in execution, so Methods and Properties are also available to primitive values.

String Length

The Length property of string returns the Length of String.

let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let totalAlphabets = alphabets.length;
console.log(totalAlphabets) // 26

Everything inside the quotes or backticks are treated as characters, Even the White Spaces.

These white spaces are also counted while determining the string length.

Finding String inside the String

The indexOf() methods returns the position of the first occurrence of a specified text of String.

let str = "The quick brown fox jumps over the lazy dog"
let position = str.indexOf("fox");
console.log(position) // 16

JavasScript counts position from zero.

0 is the first position, 1 is the second position, 2 is the third position and so on…

The lastIndexOf() methods returns the last occurrence of a specified text in a string.

let str = "big black bug bit a big black dog on his big black nose";
let lastPosition = str.lastIndexOf("black");
console.log(lastPosition) // 45

indexOf() and lastIndexOf() returns -1 if matched text not found.

Both these String Methods accepts a second parameter as the starting position for the search.

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);
console.log(pos) // 7

Searching A String within a String

The search() method searches for a string within a string and returns the position of the match.

let str = "The quick brown fox jumps over the lazy dog"
let position = str.search("fox");
console.log(position) // 16

Something to Notice Here —

The Methods indexOf() and search() accept the same parameter and returned the same result.

Are they Same? No!

The Difference is —

  1. The search() method cannot take the second parameter i.e Starting Point Position.
  2. The indexOf() cannot take regular expressions as an argument.

Extracting Parts from the String

The slice() method extracts a part of the string and returns the new string.

This method takes 2 parameters —

  1. The Start position
  2. The End position (Ending Position is Not Included) (optional)
let animals = "Cat, Dog, Monkey, Cow"
let result = animals.slice(5, 8);
console.log(result) // Dog

This example slices out the position of string from 5 to 8 and returns us a new String.

JavaScript begins counting from 0. First position is 0.

slice() method also accepts a negative parameter, the position is counted from the end of the string.

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.slice(-16, -13);
console.log(result) // Dog

The second parameter is optional if you omit it the method will slice out the rest of the string.

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.slice(5);
console.log(result) // Dog, Monkey, Cow

or …

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.slice(-16);
console.log(result) // Dog, Monkey, Cow

Remember: The Negative Parameters do not work for some Older Browsers

The substring() method

substring() is similar to slice() just this method cannot accept negative values.

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.substring(5, 8);
console.log(result) // Dog

Similarly, like slice() if you omit the second parameter in substring() it will slice out rest of the string.

The substr() method

substr() is similar to slice(), the difference is that the second parameter specifies the exact length of the string.

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.substr(5, 11);
console.log(result) // Dog, Monkey

Again here, If you omit the second parameter it will slice() rest of the string.

If the first parameter is negative, the position counts from the end of the string.

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.substr(-11);
console.log(result) // Monkey, Cow

Replacing the content inside the string

The replace() method replaces the matched value with another value in the string.

let animals = "Cat, Dog, Monkey, Cow"
let result = animals.replace("Dog", "Donkey");
console.log(result) // Cat, Donkey, Monkey, Cow

replace() method does not mutate the original string, it returns the new string.

By Default, the replace() method replace only the first match and is case sensitive.

let animals = "Cat, Dog, Monkey, Cow, Dog"
let result = animals.replace("Dog", "Donkey");
console.log(result) // Cat, Donkey, Monkey, Cow, Dog

How to convert string to Uppercase and Lowercase?

The String is converted to upper case with toUpperCase() method.

let animals = "Cat, Dog, Monkey, Cow, Dog"
let result = animals.toUpperCase();
console.log(result) // CAT, DOG, MONKEY, COW, DOG

The String is converted to lower case with toLowerCase() method

let animals = "Cat, Dog, Monkey, Cow, Dog"
let result = animals.toLowerCase();
console.log(result) // cat, dog, monkey, cow, dog

Joining Strings

The concat() methods add (joins) two or more strings.

let animals_1 = "Cat, Dog, Monkey";
let animals_2 = "Cow, Dog";
let result = animals_1.concat(", ",animals_2);console.log(result) // Cat, Dog, Monkey, Cow, Dog

concat() method returns new String and it does not mutate the original string.

Trimming Strings

The trim() method removes white space from both the side of the String.

let str = "   Hello World            ";
let trimmedString = str.trim();
console.log(trimmedString); // Hello World

The trim() method is not supported in IE 8 or Earlier.

Accessing the Character and Character Code.

The charAt() method returns the character at a particular position of the string.

let animals = "Cat, Dog, Monkey";
let sixthCharacter = animals.charAt(6);
console.log(sixthCharacter); // o

JavaScript begins counting from 0. First position is 0.

Now, let us get the Character Code of a particular Character.

The charCodeAt() method returns the character code of the Character.

let animals = "Cat, Dog, Monkey";
let sixthCharacter = animals.charAt(6);
console.log(sixthCharacter); // olet characterCode = animals.charCodeAt(6);console.log(characterCode); // 111

Converting a String to an Array

The split() method converts the string to an array.

This method splits the string into an array based on the parameter passed.

let animals = "Cat, Dog, Monkey";
let animalsArray = animals.split(","); // Splits String on Commas
console.log(animalsArray); // ["Cat", " Dog", " Monkey"]animalsArray = animals.split(" "); // Splits String on Spaceconsole.log(animalsArray); // ["Cat,", "Dog,", "Monkey"]

If no parameter is passes split() will return the whole string in index[0].

If the parameter is “” , it will return the array of Single Character.

let animals = "Cat, Dog, Monkey";
let animalsArray = animals.split(""); // Splits String on Commas
console.log(animalsArray); // ["C", "a", "t", ",", " ", "D", "o", "g", ",", " ", "M", "o", "n", "k", "e", "y"]

Summary

  • There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions i.e ${…}
  • Use slice and substring to get substring.
  • To lowercase/uppercase a string, use — toLowerCase or toUpperCase
  • str.trim() – removes (“trims”) spaces from the beginning and end of the string
  • str.split() — Splits the string into an array.

--

--