DEV Community

developedbyjk
developedbyjk

Posted on

W3Schools Strings Method With Example

Here are Strings Method that I learned on W3schools
you can copy paste it and check the output and experiment with it

/*
IN JAVASCRIPT
strings are primitve values and they dont have mehthod or properties
BUT
JS consider stings as objects so  we can use mehthod and properties with Srings


*/

let text = "Hello World Hello";

//returns the lenght of the text
console.log(text.length);

//extracting the strings from inde
console.log(text.slice(2,5));

//extracting the string if its negative then starts from back
console.log(text.slice(-1,));

//extractin the string : (from, no of amount to extract);
console.log(text.substr(2, 6));

//replace the specific World
console.log(text.replace("Hello","Bye"));
/*
if we have text as >>>>> "Hellow my world you are hello"
:  text.replace("Hello","bye"); >> will replace only 1st hello
: to replace all 'Hello' we use : text.replace("/Hello/g","bye");

*/

console.log(text.replace("/Hello/g","bye"));
// or we can use

console.log(text.replaceAll("Hellow", "bye"));

//to upper case
console.log(text.toUpperCase());

// to lower case
console.log(text.toLowerCase());

// now its time to trim so
console.log("TRIMMING  " +  text.trim());

// adding some before num
//if its nume first we need to convet it into strings
let padnum = "hey bitch";
let convert = padnum.toString();
let padstart = convert.padStart(10,"o");
console.log(padstart);

//SAme you can do with pad end
var name = "bhag";
let outputofname = name.padEnd(50," bhai ");
console.log(outputofname);

//Extracting String Character at specific position
console.log(text.charAt(9));

//Extracting String Character code at specific position
console.log(text.charCodeAt(9));

// you can also do this
console.log(text[9]);

//Converting String to arrays 
var convertedtoarray = text.split(" ");
console.log(convertedtoarray[2]);
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)