Most Usages of String methods in JavaScript

Md. Mostafa Al Mahmud
5 min readNov 2, 2020

--

For regular updating and matching with the top languages, JavaScript has ranked as one of the most popular and essential programming languages of all time. Javascript is a high-level language that has curly bracket syntax, dynamic coding style & prototype-based language on object-oriented programming.

There are six data types in JavaScript such as:

  • undefined
  • Boolean
  • Number
  • String
  • BigInt
  • Symbol

Today I will discuss most usages methods of String data type in JavaScript. Let’s get started.

JavaScript strings are mostly used to sort and manipulate the text. It's a sequence of Unicode characters. In general, since primitive values are not considered as an object, they have not properties and methods. But most surprisingly in JavaScript, primitive values have methods and properties because of considering them as an object in JavaScript by default.

1. Length() method

When we need the length of a string, we use the string method. It returns the number of characters of a string.

const text = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;const txtLengh = text.length;console.log(txtLengh);
// 62

2. indexOf() method

Find the position (index) of the first occurrence of the specified text in a string. For example;

const str = "I love Bangladesh. Bangladesh is a beautiful country";let idxAsFirst = str.indexOf("Bangladesh");console.log(idxAsFirst);
// 7

Also, you can use the second argument to search from that position

console.log(str.indexOf(“Bangladesh”, 1));
// 7

If any value is not found, it returns a false value as -1

console.log(str.indexOf(“Mostafa”));
// -1

If you pass an argument that does not exist, returns false also as -1

console.log(str.indexOf(“Bangladesh”, 50));
// -1

3. lastIndexOf() method

Find the position of (index) the last occurrence of the specified text in a string

const str = “I love Bangladesh. Bangladesh is a beautiful country”;
let idxAsLast = str.lastIndexOf("Bangladesh")
console.log(idxAsLast);
// 19

Also,lastIndexOf() is case-sensitive. For example,

'I love Bangladesh'.lastIndexOf('i'); 
// -1

4. charAt() method

Find the character of a specific position. It represents the character (exactly one UTF-16 code unit) at the specified index. Whenindex is out of range, charAt() returns an empty string.

const str = 'I love javascript';const idx= 7;console.log(`The character at index ${idx} is ${str.charAt(idx)}`);
// "The character at index 7 is j"

Also, String behaves as an array-like object, not an array indeed. For example;

console.log(str[7]); 
// j

5. replace() method

replace()replace the text with the given argument

const str = 'I love javascript';const replacedTxt = str.replace("love", "like")console.log(replacedTxt);
// I like Bangladesh.

For using global replace and affects each occurrence of the matched texts, we have to use a regular expression. For example,

let regex = /Php/gi;
let str = 'I like Php and Php is suit for me';
let newStr = str.replace(regex, 'JavaScript');console.log(newStr);
// I like JavaScript and JavaScript is suit for me.

6. slice() method

slice() The first argument indicates from which it starts to be and the second argument indicates the endpoint that means it extracts a part of a string and returns it as a new string, except changing the original value.

const str = “I love Bangladesh. Bangladesh is a beautiful country”;
console.log(str.slice(0, 18));
// I love Bangladesh
console.log(str.slice(19, 52));
// Bangladesh is a beautiful country

You can use a negative index that means it counts from the last occurrence.

console.log(str.slice(-18, -7));
// beautiful
console.log(str.slice(-7, (str.length — 0)));
// country

It is easy to get using one argument with a negative value when we want to catch from a specific point to the endpoint of a sentence

console.log(str.slice(-7));
// country

7. split() method

split() is a method that divides a string by searching a pattern that is provided as the first parameter in the method call like ('') (' '),() or anything else into an ordered list of substrings creates an array as substrings and returns the array.

split with the condition at empty space and divied by words and returns all words in an array

const str = “I love Bangladesh. Bangladesh is a beautiful country”;
const splitWords = str.split(' ');
console.log(splitWords);
/*
[ 'I',
'love',
'Bangladesh.',
'Bangladesh',
'is',
'a',
'beautiful',
'country'
]
*/

Split with no space and divided by characters one by one

const splitChars = str.split('');console.log(splitChars);
/*
[ 'I', ' ', 'l', 'o', 'v', 'e', ' ', 'B', 'a', 'n', 'g', 'l', 'a', 'd', 'e', 's', 'h', '.', ' ', 'B', 'a', 'n', 'g', 'l', 'a', 'd', 'e', 's', 'h', ' ', 'i', 's', ' ', 'a', ' ', 'b', 'e', 'a', 'u', 't', 'i', 'f', 'u', 'l', ' ', 'c', 'o', 'u', 'n', 't', 'r', 'y' ]
*/

Split without any condition and returns a full string

const splitFull = str.split();console.log(splitFull);
// [ 'I love Bangladesh. Bangladesh is a beautiful country' ]

8. includes() method

includes() checks whether one string or a value is found in a string and returns true or false as a boolean value.

const str = “I love Bangladesh. Bangladesh is a beautiful country”;
let word = “Bangladesh”
console.log(`The word “${word}” ${str.includes(word) ? ‘is’ : ‘is not’} in the sentence`);
// The word "Bangladesh" is in the sentence
word = “US”console.log(`The word “${word}” ${str.includes(word) ? ‘is’ : ‘is not’} in the sentence`);
// The word "US" is not in the sentence

9. substr() method

substr()returns a part of a given string that is started from the first argument indexed position and ended as the second argument indexed number, not like the counting characters likesubString() method

const str = “I love Bangladesh. Bangladesh is a beautiful country”;
console.log(str.substr(1, 5));
// love

When one argument is passed, it is started from that position to the end of the string

console.log(str.substr(35));
// beautiful country

Another example of using substr()when booleanvalue is need as a return value

console.log((‘Bangladesh’.substr(9) !== ‘h’));
// false
console.log((‘Bangladesh’.substr(-1) === ‘h’));
// true

10. concat() method

concat() combines the string arguments and returns a new string. This method is used to join two, three, or more strings not changing the existing strings. It returns a new string

For example,

const s1 = ‘Mostafa’;console.log(‘Hi’.concat(‘ ‘, s1));
// Hi Mostafa

Another example,

let greetings = ['Hi', ',', '', 'Mostafa', '!']console.log("".concat(…greetings));
// Hi, Mostafa!

These all are the essential string method in JavaScript that we use in our real programming life as well.

If this article is helpful to you, do not forget to clap, follow me.

Thanks a lot.

--

--

Md. Mostafa Al Mahmud
Md. Mostafa Al Mahmud

Written by Md. Mostafa Al Mahmud

Full-Stack Software Engineer || JavaScript Lover || Experienced with MERN Stack || Mongo, Express, React, Node, ES6, Netlify, Heroku, Firebase, Version Control

Responses (1)