DEV Community

ahmadullah
ahmadullah

Posted on

JS String methods #3

As we studied yesterday about split() method means this method we can remove any character or space from our sentence.

let password='udgtj 9e59 jfd';
let correctPassword=password.split(' ');
console.log(correctPassword);
//result -> ['udgtj','9e59','jfd'];
Enter fullscreen mode Exit fullscreen mode

There is a method which is for array and the split() method returns an array so we can use join() method that joins array items.

let correctPassword=password.split(' ');
correctPassword.join('');
console.log(correctPassword);
//result -> udgtj9e59jfd
Enter fullscreen mode Exit fullscreen mode

we can use this method along with the split() method.
So keep going and practicing this method with split() method and indexOf() method.

charAt() method

This method is versus indexOf() method.
This method requires the position of a character to return the character we want.

let name='john';
console.log(name.charAt(1));
//result -> o
Enter fullscreen mode Exit fullscreen mode

slice() method

This method extracts a section of a string and returns it as a new string.
This method takes two arguments.
I mentioned argument which we'll learn in functions section.
The first argument which is required start index and the second is end index.
if we do not specify the end index the slice() method will extracts a string from start index up to end index.

let greeting='hi Nikolas! My name is ahmad';
let halfGreeting=greeting.slice(3);
console.log(halfGreeting);
//result -> Nikolas! name is ahmad
Enter fullscreen mode Exit fullscreen mode

If we specify the end index the result will be different.

let greeting='hi Nikolas! My name is ahmad';
let halfGreeting=greeting.slice(3,10);
console.log(halfGreeting);
//result -> Nikolas
Enter fullscreen mode Exit fullscreen mode

The slice method does not include the end index it means that it subtract one from endIndex-1;
which does not return the end index.

Oldest comments (0)