Methods in Javascript
Following are the useful methods of String in JavaScript
Declaration and interpolation of string:-
let name = "pashupati"
const adharId = "84930384939"
Using
let
:Declare a variable:
let name;
Assign a string value:
name = "pashupati";
Using
const
:Declare a constant variable:
const adharId = "
84930384939";
String Interpolation:-
A common way to achieve string interpolation in JavaScript is by using template literals. Here's an example:
console.log(`my real name is ${name} and my adharnumber ${adharId}`);
Sample code to understand below related code:-
let gameName = new String ("Pubgmob") console.log(gameName);
Following are the methods of string in JavaScript:-
Length
toUpperCase
charAt
indexOf
substring
slice
trim
replaces
includes
Length Method:-
let gameName = new String ("Pubgmob") console.log(gameName.length);
0=>P
1=>u
2=>b
3=>g
4=>m
5=>o
6=>b
Uppercase Method:-
let gameName = new String ("Pubgmob") console.log(gameName.toUpperCase);method do operation on the string n make string in uppercase
method do operation on the string and make string in uppercaseOriginal.
The string is not changed Due to the heap memory Concept.
charAt:-
let gameName = new String ("Pubgmob")
console.log(gameName.charAt(2));
- To know which string character is at the position of index no.2
indexOf:-
let gameName = new String ("Pubgmob")
console.log(gameName.indexOf('u'));
To know the string character (given in the console log) at which index no.
substring:-
let gameName = new String ("Pubgmob")
let newGameName = gameName.substring(0, 3)
it gives the values from index no.0 to index no.2 (Excluded end parameter)it does
take negative values like a slice
slice:-
let gameName = new String ("Pubgmob")
let anotherGameName = gameName.slice(1, 5)
it gives value from index no,1 to index no.5
it takes the value of index no.5
Trim:-
let gameName = new String ("Pubgmob")
let anotherGameName = gameName.slice(-6, 3)
Negative values are allowed in the slice method unless like substring
-6===> It counts value back from index no.6 to index no.3
Replace:-
const url = "pashuapti20%bansode.com"
console.log(url.replace('20%', '-'))
- The replace method will find the 20% inside the string and it is replaced by -
includes:-
const url = "pashuapti20%bansode.com"
console.log(url.includes('pashuapati'));
it will ask the question to string like is pashuapti present in the string?
it returns the value in a boolean like true or false.