DEV Community

Cover image for JS Basic String Methods
Shshank
Shshank

Posted on

JS Basic String Methods

Here is a list of few basic string methods:

  • Length, check length of a string
const myString = "I love coding";
console.log(myString.length);
Enter fullscreen mode Exit fullscreen mode
  • Trim, remove whitespaces at the beginning and at the end of string.
const myString = "  I love coding  ";
console.log(myString.length); // 17
console.log(myString.trim()); // "I love coding"
console.log(myString.trim().length); // 13
Enter fullscreen mode Exit fullscreen mode
  • Split, convert a string to an array.
const myString = "I love coding";
const arr = myString.split(" ");
console.log(arr);
// ['I', 'love', 'coding'];
Enter fullscreen mode Exit fullscreen mode
  • Includes, returns true if a string contains a particular string. In other case return false.
const myString = "I love coding";
if(myString.includes("coding")) {
 console.log('yes');
} else {
 console.log('no');
}
// yes
Enter fullscreen mode Exit fullscreen mode
  • Char At, get the character at a specific position in a string.
const myString = "I love coding";
const myChar = myString.charAt(7);
console.log(myChar); // c
Enter fullscreen mode Exit fullscreen mode
  • Slice, extract a part of a particular string.
const myString = "I love coding";
const text = myString.slice(2,6);
console.log(text); // love
Enter fullscreen mode Exit fullscreen mode
  • To lower case, convert the string to lowercase letters.
const myString = "I LOVE CODING";
console.log(myString.toLowerCase());
// i love coding
Enter fullscreen mode Exit fullscreen mode
  • ** To upper case**, convert the string to uppercase letters.
const myString = "I love coding";
console.log(myString.toUpperCase());
// I LOVE CODING
Enter fullscreen mode Exit fullscreen mode
  • Replace, returns a new string with a text replaced by different text.
const myString = "I love coding";
const replacedSring = myString.replace('coding', 'programming');
console.log(replacedString);
// I love programming
Enter fullscreen mode Exit fullscreen mode
  • Concat, concat string arguments to a particular string.
const myString = "I love coding";
const newString = "& designing";
const concatedString = myString.concat(' ', newString);
// I love coding & designing
Enter fullscreen mode Exit fullscreen mode
  • Starts with, returns true if a string starts with a particular string.
const myString = "I love coding";
myString.startsWith('coding') ? (console.log('yes')) : console.log('no'));
// no
Enter fullscreen mode Exit fullscreen mode
  • Ends with, returns true if ends with a particular string.
const myString = "I love coding";
myString.endsWith('coding') ? (console.log('yes')) : console.log('no'));
// yes
Enter fullscreen mode Exit fullscreen mode

I hope you find these functions helpful. You can also share more functions in the comment section.

Thank You.

Top comments (0)