DEV Community

Cover image for 8 Useful JavaScript String Methods
Rahul
Rahul

Posted on

8 Useful JavaScript String Methods

A JavaScript string stores a series of characters like "Rahul". String indexes are zero-based: The first character is in position 0, the second in 1, and so on. So here in the post, we're gonna see some of these useful string methods you can use for your projects to save your time and increase your productivity.



Do you want development news right on your default chrome or firefox page? Then get the amazing daily.dev extension. There are only PROS of getting this extension no CONS.

Let's Start 🤘🙌

1. indexOf

The indexOf() method returns the index of (the position of) the first occurrence of a specified text.

const str ='I have Css, Wait I love CSS'
str.indexOf('Css');

// 7
Enter fullscreen mode Exit fullscreen mode

2. length

The length property returns the length of a string.

const str = 'ILoveCss'
str.length;

// 8
Enter fullscreen mode Exit fullscreen mode

3. slice

slice() extracts a part of a string and returns the extracted part in a new string.

const str = 'ILoveCss';
str.slice(2,5);

// ove
Enter fullscreen mode Exit fullscreen mode

4. replace

The replace() method replaces a specified value with another value in a string.

const str = 'IHateCss';
str.replace('Hate', 'Love');

//ILoveCss
Enter fullscreen mode Exit fullscreen mode

5. upper and lower case

This method converts a string to lowercase or uppercase

const str="ILoveCss";
str.toLowerCase();
// ilovecss

str.toUpperCase();
// ILOVECSS
Enter fullscreen mode Exit fullscreen mode

6. trim

The trim() methods removes whitespace from both sides of the string

const str = '        ILoveCss'      ;
str.trim();

// ILoveCss
Enter fullscreen mode Exit fullscreen mode

7. concat

concat() joins two or more strings. The concat() method can be used instead of the plus operator

const str = 'Ilove';
str.concat('Css')

// ILoveCss
Enter fullscreen mode Exit fullscreen mode

8. split

A string can ve converted to an array with the split() method

const str = 'I,Love,Css'; 
str.split(',');

// ['I', 'Love', 'Css']
Enter fullscreen mode Exit fullscreen mode

Don't forget to get the daily.dev extension.




Thanks For Reading. 🙂

Hope you like the content. And plz surely comment if you want to add something to this. 🙌😎

Top comments (0)