String cheatsheet in Javascript
Strings cheatsheet in Javascript
If you want to become a good Developer then you must need to have a good command over the basics of the language you're dealing with. When it comes to Javascript, Strings are one of the strong pillars. Now we are going see some of the methods that you can apply on strings.
String cheatsheet
For this post we are going to use this example
const sentence = 'Hello onecompiler'
So lets get started!
1. length
// sentence.length => returns the length of string
console.log(sentence.length) // output: 17
2. indexOf()
// sentence.indexOf('Hello') => returns the staring index of first occurence, if not found returns -1
console.log(sentence.indexOf('Hello')) // output: 0
3. lastIndexOf()
// sentence.indexOf('Hello') => returns the staring index of last occurence, if not found returns -1
console.log(sentence.lastIndexOf('Hello')) // output: 0
4. replace()
// sentence.replace('Hello', 'Hey') => replaces the first string with second
console.log(sentence.replace('Hello', 'Hey')) // output: Hey onecompiler
5. substr()
// sentence.substr(1,2) => returns substring starting from index 5 of length 2
console.log(sentence.substr(1,2)) // output: el
// if we ignore length param
console.log(sentence.substr(1)) // output: ello onecompiler
6. includes()
// sentence.includes('Hello') => checks if a string exists in given string (case-sensitive)
console.log(sentence.includes('Hello')) // output: true
7. endsWith()
// sentence.endsWith('Hello') => checks if a string ends with given string (case-sensitive)
console.log(sentence.endsWith('Hello')) // output: false
8. startsWith()
// sentence.startsWith('Hello') => checks if a string starts with given string (case-sensitive)
console.log(sentence.startsWith('Hello')) // output: true
9. charAt()
// sentence.charAt(1) => character at index 1
console.log(sentence.charAt(1)) // output: 'e'
10. toUpperCase()
// sentence.toUpperCase() => convert string into uppercase
console.log(sentence.toUpperCase()) // output: HELLO ONECOMPILER
11. toLowerCase()
// sentence.toLowerCase() => convert string into lowercase
console.log(sentence.toLowerCase()) // output: hello onecompiler
12. trim()
// sentence.trim() => removes spaces at start and end
console.log(sentence.trim()) // output: hello onecompiler
13. slice()
// sentence.slice(0,4) => returns a substring from specified indexes
console.log(sentence.slice(0,4)) // output: hello
14. split()
// sentence.split() => splits into strings seperated by spaces
console.log(sentence.slice(0,4)) // output: ['hello', 'onecompiler']
That's it guys, cheers!