String and its methods in Javascript

String and its methods in Javascript

What are Strings?

The string object is used to represent and manipulate a sequence of characters.

1.at():

This method takes the argument as an index to find the value at that index, it works for both positive and negative values.

const sentence = 'The quick brown fox jumps over the lazy dog.';
let index = 5;

console.log("The value at given index 5 is " + sentence.at(5) + "it also works for negative value for -2 is " + sentence.at(-2));

O/P: The value at given index 5 is u  it also works for negative value for -2 is g

2.length():

This method is used to find out the length of a string.

const data = "be aware"
console.log(data.length);

O/P: 8

3.slice():

This method extracts a part of string and returns that into a new string. It works on positive as well as negative values.

let st1 = "Dont forget to smile today";
let st1_part = st1.slice(0,4);
console.log(st1_part);

let st1_part1 = st1.slice(-11,-6);
console.log(st1_part1);

O/P: Dont
smile

4.substring():

This method is same as the slice but the start and end values in negative are treated as 0 only and no output is provided if only one negative value is provided it will print the whole string.

let st1 = "Dont forget to smile today";
let st1_part = st1.substring(0,4);
console.log(st1_part);  op--> Dont

let st1_part1 = st1.substring(-11,-7);
console.log(st1_part1); op--> blank

let st1_part1 = st1.substring(-11);
console.log(st1_part1); op--> Dont forget to smile today

5.substr():

This method takes two arguments first denotes where to start and the other denotes the length of the part. if a single argument is given then it will give the rest of the string. If both negative values are provided then it returns nothing and if a single negative is provided then it will count backward.

let st1 = "Dont forget to smile today";

let st1_part = st1.substr(0,11);
console.log(st1_part); O/P: Dont forget

let st1_part1 = st1.substr(15);
console.log(st1_part1); O/P: smile today

let st1_part2 = st1.substr(-11,-5);
console.log(st1_part2); O/P: blank

let st1_part3 = st1.substr(-8);
console.log(st1_part3); O/P: to smile today

6.replace():

This method returns a new string with the one that matches the condition. The pattern can be a string or a regular expression.

let st1 = "Dont forget to smile today";

let st1 = "Dont forget to smile today";
const regex = /Dont/i;
let st1_part = st1.replace(regex,"do");
console.log(st1_part); O/P: do forget to smile tommorow

let st1_part = st1.replace("today","tommorow");
console.log(st1_part); O/P: Dont forget to smile tommorow

let st1_part2 = st1.replace("Today","tommorow");
console.log(st1_part2); O/P: Dont forget to smile today

let st1_part3 = st1.replace(/Today/i,"tommorow");
console.log(st1_part3); O/P: Dont forget to smile tommorow

7.replaceAll():

let st1 = "Dont forget to smile today";
let st1_part1 = st1.replaceAll(/T/g,"d");// Case sensitive wont work
console.log(st1_part1); O/P--> Dont forget to smile today

let st1_part2 = st1.replaceAll(/o/g,"d");
console.log(st1_part2);O/P--> Ddnt fdrget td smile tdday

8. toUpperCase() and toLowerCase():

This method returns a new string after converting it into lower or upper case.

let st1 = "Dont forget to smile today";
str2 = st1.toLowerCase()
console.log(str2); O/P--> dont forget to smile today
console.log(st1);O/P--> Dont forget to smile today

str3 = st1.toUpperCase()
console.log(str3); O/P--> DONT FORGET TO SMILE TODAY

9.concat():

This method joins one string after another.

let str1 = "Dont forget to ";
let str2 = "smile today";
let str3 = str1.concat(str2);
console.log(str3);
O/P--> Dont forget to smile today

10.trim() , trimStart(), trimEnd():

This methods trims the whitespaces. trim removes all of the whitespaces , trimstart removes from starting and trim end removes from end.

let str1 = "    Dont forget to      ";
let str2 = str1.trim(); //remove whitespace start and end
console.log(str2);
O/P--> Dont forget to

let str2 = str1.trimStart(); //remove whitespace from start
console.log(str2);
O/P--> Dont forget to

let str2 = str1.trimEnd(); //remove whitespace from end
console.log(str2);
O/P-->     Dont forget to

11. padStart() and padEnd()

This method adds padding at the start and end respectively. It takes two arguments first for length and second for pad string.

let str1 = "keep it simple";
let accountnumber = "48899200006575"
let str2 = str1.padStart(19,"x"); // the length of str1 is 14 
// so it will add 19-14= 5 times the elemnt provided
let last4Digits =( accountnumber.slice(-4));
const maskedNumber = last4Digits.padStart(accountnumber.length, '*');
console.log(str2); O/P--> xxxxxkeep it simple
console.log(maskedNumber);O/P--> **********6575

12.charAt():

This method returns the character at given index.


let str1 = "keep it simple";
let str2 = str1.charAt(5);
O/P--> i

13.charCodeAt():

This method returns the Unicode of the character at a specified index (position) in a string.

let str1 = "keep it simple";
let str2 = str1.charCodeAt(5);
O/P--> 105

14.split():

This method splits a string into an array of substrings.

let str1 = "keep it simple";
let str2 = str1.split("");
let str3 = str1.split("");

console.log(str2);
O/P-->['k', 'e', 'e', 'p', ' ', 'i', 't', ' ', 's', 'i', 'm', 'p',  'l', 'e']

console.log(str2);
 O/P--> [ 'keep', 'it', 'simple' ]

15.indexOf() and lastIndexOf():

This method returns the position of the first occurrence of a value in a string and last index of gives the last occurence of the value in a string.

let str1 = "the main reason of enjoying the small steps"
console.log(str1.indexOf("the")); O/P-->0 // search from start
console.log(str1.indexOf("z")); O/P--> -1
console.log(str1.indexOf("e",20)); O/P--> 30 //search starts from 20

console.log(str1.lastIndexOf("the")); O/P--> 28 // search from end
console.log(str1.lastIndexOf("z")); O/P--> -1
console.log(str1.lastIndexOf("e",10)); O/P--> 10 //search starts backwards  from 10

16.search():

This method executes a search for a match between a regular expression and this string object.It can work for normal values also.

The difference between indexof() and the search() is that search method don't take second arguments and it can work for regular expression also.

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// expected output: 43

17. match() :

This method gives the matching result against a regular expression.

const paragraph = 'We all grow at a different pace and thats totally ok';
const regex = /[x-z]/i;
const dekho = paragraph.match(regex);
console.log(dekho); O/P:
[ 'y',
  index: 48,
  input: 'We all grow at a different pace and thats totally ok',
  groups: undefined]

18.includes():

This methods returns true if the string contains the given string and false if it does not contain the string. It is case sensitive.

let str1 = "the main reason of enjoying The small steps"
console.log(str1.includes("am")); O/P: True
console.log(str1.includes("mam")); O/P: False

let str1 = "the main reason of enjoying The small steps"
console.log(str1.includes("re",9)); O/P: True // Start from 9

19. startsWith() and endsWith():

This method return true or false if it starts or ends with the given string.

let str1 = "keep it simple";
console.log(str1.startsWith("keep")); O/P: True
console.log(str1.startsWith("keep",2));// starting index is 2 
O/P: False

21.codePointAt():

What is Unicode?

It is an encoding for textual characters which can represent characters from many different languages from around the world. Each character is represented by a Unicode code point.

This method returns the Unicode point at a given position.

///codePointAt()
let str1 = "Dont forget to smile today";
console.log(str1.codePointAt(3));
O/P --> 116

21.fromCharCode():

This method returns a string created from the specified sequence of UTF-16 code units.

What is UTF-16?

UTF-16 is an encoding of Unicode in which each character is composed of either one or two 16-bit elements.

console.log(String.fromCharCode(3)); O/P--> ♥
console.log(String.fromCharCode(3)); O/P--> ♦

22.localCompare():

This method returns a number if the given string comes before, or after, or is the same as the given string in sort order. if it is equal then it returns 0,if it comes after then it returns 1 and if it comes before then it gives -1.

let t1 = "you have to beleive the power of compound effect";
let t2 = "have";
let t3 = "you have to beleive the power of compound effect";

let result = t1.localeCompare(t2);
let result1 = t1.localeCompare(t3);
console.log(result); O/P--> 1
console.log(result1); O/P--> 0

23.normalize():

This method returns the Unicode Normalization Form of the string.

var f  = '\u0041\u006d\u00e9\u006c\u0069\u0065';
let b = f.normalize('NFC')
console.log(b); O/P--> Amélie

24.raw():

This method is used to get the raw string form of template literals.

let filePath = String.raw`C:\Development\fsjs2\strings`;

console.log(`The file was uploaded from: ${filePath}`);

O/P--> The file was uploaded from: C:\Development\fsjs2\strings

25.repeat():

This method returns a string with a number of copies of a string.

let text = "It is a whole new day";
let result = text.repeat(3);
console.log(result);
O/P--> It is a whole new dayIt is a whole new dayIt is a whole new day

26.toLocaleLowerCase() and toLocaleUpperCase():

This method converts a string to lowercase letters or upper letters, using current locale and the locale is totally based on the current setting of the browser.

let firstst = "once in a lifetime";
let secondst = "Hello World!";
let result = firstst.toLocaleUpperCase();
let result1 = secondst.toLocaleLowerCase();
console.log(result); O/P-->ONCE IN A LIFETIME
console.log(result1); O/P-->hello world!