JavaScript Strings and Strings Method

Time to learn how to deal with these javascript strings4 min


Javascript strings are a sequence of characters enclosed in a quotation mark (” “).

Advertisements

Strings can be anything enclosed in a quotation mark including empty spaces. Today, we will cover every string method you can use in JavaScript.

EXAMPLES OF STRINGS

  • “This is a string”
  • ” “
  • “08078787873”
  • “!05627@41&48!8” etc

You see that no matter the character, once enclosed in a quotation mark, it is treated as a string and this can be confirmed by running the typeof() operator

typeof("!05627@41&48!8") //string
typeof(" ") //string

ALL STRING METHODS

length

This property returns the number of characters in a string.

let word = "Butterfly";
word.length; // 9

let sentence = "Life is not a bed of roses";
sentence.length; //26

let name = " ";
name.length; // 1 empty spaces are also counted.

charAt( )

This method can be read out as “character at” and it returns a single character situated at that position defined as the argument. This position should be a number between 0 and 1 less than the length of the string.

Note: JavaScript count indexes from zero (0), the first letter is usually indexed at 0.

let word = "Butterfly";
console.log( word.charAt(2) ) // 't'

let sentence = "I am leaning JavaScript at ConcatDevs";
sentence.charAt(10) //'n'

let name = "Billy";
name.charAt(0) // 'B';

charCodeAt( )

This is the sister of charAt() but this doesn’t return the actual human-readable character at that specified index but the character code.

'ABC'.charCodeAt(0); // 65
'abc'.charCodeAt(0); // 97

This shows that every character in JavaScript is unique and are not equal. thus ‘A’ is not equal to ‘a’ and vice versa.

concat( )

The concat method in JS is used to concatenate two strings together to create a new string. This new string consists of the two strings joined together. In layman terms, this joins two or more strings together to form one bigger string.

let str1 = 'Hello';
let str2 = 'World';
console.log(str1.concat(str2)); // HelloWorld

let str1 = 'Hello';
let str2 = 'World';
console.log(str1.concat(' ', str2)); //Hello World

let str1 = 'Hello';
let str2 = 'World';
let str3 = 'Big';
console.log(str1.concat(str3, str2));  //HelloBigWorld 

includes( )

This determines whether one string may be found within another string. It returns either true or false as the case may be. The calling string may be the one that contains the word to search for.

let sentence = 'The quick brown fox jumps over the lazy dog.';
sentence.includes('fox'); //true
sentence.includes('dog'); //false
sentence.includes('Fox'); //false N.b: F is different from f.

You can also add a position to begin the search from as thus

let word = 'Hello';
word.includes('H', 2); //false;

Even though the word contains the character ‘H’, it returned false because it was asked to begin its search from index 2.

indexOf( )

This is a very important method used in JS to return the index of the first occurrence of a specified character. index refers to the position of that character.

The index of the first character is 0, and the index of the last character of a string called Name is Name.length - 1. it returns -1 when it can’t find that character.

let sentence = 'The dog is eating now!';
sentence.indexOf('dog'); //4
sentence.indexOf('e'); // 2

Despite the sentence containing two “e”, it returned 2 which is the index of the first occurrence of ‘e’.

'Blue Whale'.indexOf('blue'); // returns -1 // case sensitivity

lastIndexOf( )

This method is the sister of indexOf() but this returns the index of the last occurrence of that character.

let word = 'Canal';
word.lastIndexOf('a'); //4 

let paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
paragraph.lastIndexOf('dog'); // 52

repeat( )

This returns a string consisting of the elements of the object repeated the given times. The time is passed as an argument.

Advertisements
let shout = 'hey! ';
shout.repeat(3); // 'hey! hey! hey! '

'abc'.repeat(2) // 'abcabc'

replace( )

This is used to replace a string with another string that matches the one specified. If there is no match, the replace function will not work.

let sentence = 'I am Learning JavaScript';
sentence.replace('JavaScript', 'Python'); //'I am Learning Python'

let sentence = 'I am Learning JavaScript';
sentence.replace('dancing', 'Python'); // 'I am Learning JavaScript'

slice( )

This method extracts a section of a string and returns it as a new string, without modifying the original string. It acts as a form of “copy and paste” from a specified starting position to a specified ending position.

let sentence = 'I am Learning JavaScript';
sentence.slice(0, 5); // 'I am '

let word = "Travelling";
word.slice(3, 8); //'velli'

When no ending position is specified, the string will be copied from the specified position to the very end.

let sentence = 'I am Learning JavaScript';
sentence.slice(5); //'Learning JavaScript'

let word = "Travelling";
word.slice(3); //'velling'

When a negative number is used, the copying starts from the back towards the beginning of the string.

let word = "Travelling";
word.slice(-3); // 'ing'

let sentence = 'I am Learning JavaScript';
sentence.slice(-10); // 'JavaScript'

split( )

The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

// split the string at the empty spaces

let sentence = "Cooking Laundry Gaming Programming Reading";
sentence.split(' '); 
// returns [ 'Cooking', 'Laundry', 'Gaming', 'Programming', 'Reading' ]

//split the strings at the commas

let things = 'money, cars, house, trees, phones';
things.split(','); 
//[ 'money', ' cars', ' house', ' trees', ' phones' ]

You can determine where the split should happen by placing that point as an argument. It could be open space, commas, anything.

toUpperCase( )

This converts the string to its uppercase equivalent.

let name = 'john';
name.toUpperCase(); //JOHN

let sentence = 'i am a lowercase sentence';
sentence.toUpperCase(); //'I AM A LOWERCASE SENTENCE'

toLowerCase( )

This converts the string to its lowercase equivalent

'ALPHABET'.toLowerCase(); // 'alphabet'

let name = "JOHN";
name.toLowerCase(); //john

trim( )

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

let greeting = '   Hello world!   ';
greeting.trim(); //'Hello World'

BONUS: [ ]

You can use this to select a string at a specified position.

let word = "Hello";
word[0] //'H'
word[1] //'e'
word[word.length-1] //'o'

With these string methods, you can be able to do a lot of operations on javascript involving strings. Let’s work on a few examples.

QUESTION:

Given a lowercase string, convert the first letter of that string to uppercase and return the updated string.

ANSWER:

Using the string methods at our fingerprint, we could apply so many of them to solve this. let’s take a look

Advertisements
//using the uppercase and slice method

let name = 'peter';
let updatedName = name[0].toUpperCase() + name.slice(1);

console.log(updatedName) //Peter
//using the uppercase and the replace method

let name = 'peter';
let updatedName = name.replace(name[0], name[0].toUpperCase());
console.log(updatedName); //Peter


Like it? Share with your friends!

Nnaji Victor

Legend

DecaDev, Full-stack developer in training, Gamer, Techie and weirdly cool. I love writing new stuffs that I just discovered and playing around on the net. Check my socials or email me.

What's Your Reaction?

Wow Wow
0
Wow
love love
1
love
hate hate
0
hate
geeky geeky
0
geeky
win win
0
win

0 Comments

Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item

Send this to a friend