Here is a list of few basic string methods:
- Length, check length of a string
const myString = "I love coding";
console.log(myString.length);
- 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
- Split, convert a string to an array.
const myString = "I love coding";
const arr = myString.split(" ");
console.log(arr);
// ['I', 'love', 'coding'];
- 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
- 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
- Slice, extract a part of a particular string.
const myString = "I love coding";
const text = myString.slice(2,6);
console.log(text); // love
- To lower case, convert the string to lowercase letters.
const myString = "I LOVE CODING";
console.log(myString.toLowerCase());
// i love coding
- ** To upper case**, convert the string to uppercase letters.
const myString = "I love coding";
console.log(myString.toUpperCase());
// I LOVE CODING
- 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
- 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
- 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
- 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
I hope you find these functions helpful. You can also share more functions in the comment section.
Thank You.
Top comments (0)