DEV Community

Cover image for All JS String Methods In One Post!
Aya Bouchiha
Aya Bouchiha

Posted on • Updated on

All JS String Methods In One Post!

Hello everybody, I'm Aya Bouchiha, on this beautiful day we're going to discuss all string methods in
Javascript!

Firstly, we need to know that all All methods do not change the original string, they return a new one.

concat()

  • concat() : this method links together two strings or more.
const firstName = 'Aya ';
const lastName = 'Bouchiha';
// 3 methods to concatenate two strings
console.log(firstName.concat(lastName)); // Aya Bouchiha
console.log(firstName +  lastName); // Aya Bouchiha
console.log(`${firstName}${lastName}`); // Aya Bouchiha
Enter fullscreen mode Exit fullscreen mode

match()

  • match(): used to searches a string for a match against a regular expression, and returns the matches as an Array.
const quote =  "If you don't know where you are going, any road will get you there.";
console.log(quote.match(/you/g)) // [ "you", "you", "you" ]
Enter fullscreen mode Exit fullscreen mode

matchAll()

  • matchAll(): returns an iterator of all results matching a string against a regular expression, including capturing groups. more details...
const conversation = `Hi, I'm Aya Bouchiha\nHello, I'm John Doe, nice to meet you.`;

const matchedArrays = [...conversation.matchAll(/I'm\s(?<firstName>[a-zA-Z]+)\s(?<lastName>[a-zA-Z]+)/gi)];

console.log(matchedArrays[0])

for (let matchedArray of matchedArrays) {
  const {firstName, lastName} = matchedArray['groups']
  console.log(firstName, lastName)
}
Enter fullscreen mode Exit fullscreen mode

Output:

[
  "I'm Aya Bouchiha",
  'Aya',
  'Bouchiha',
  index: 4,
  input: "Hi, I'm Aya Bouchiha\nHello, I'm John Doe, nice to meet you.",
  groups: [Object: null prototype] { firstName: 'Aya', lastName: 'Bouchiha' }
]

Aya Bouchiha
John Doe
Enter fullscreen mode Exit fullscreen mode

split()

  • split(separator) : convert a string to an array by splitting it into substrings.
const allLetters = 'abcdefghijklmnopqrstuvwxyz'; 
console.log(allLetters.split())
console.log(allLetters.split(''))

const emails = 'developer.aya.b@gmail.com,johndoes@gmail.com,simon.dev@gmail.com';
console.log(emails.split(',')) 
Enter fullscreen mode Exit fullscreen mode

Output:

[ 'abcdefghijklmnopqrstuvwxyz' ]

[
  'a', 'b', 'c', 'd', 'e', 'f',
  'g', 'h', 'i', 'j', 'k', 'l',
  'm', 'n', 'o', 'p', 'q', 'r',
  's', 't', 'u', 'v', 'w', 'x',
  'y', 'z'
]

[
  'developer.aya.b@gmail.com',
  'johndoes@gmail.com',
  'simon.dev@gmail.com'
]
Enter fullscreen mode Exit fullscreen mode

replace()

  • replace(searchString, newValue): is a method that returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If a pattern is a string, only the first occurrence will be replaced.more details
const email = 'john.doe@gmail.com';
console.log(email.replace('@gmail.com', '')); // john.doe
console.log(email.replace(/@[a-z]+.[a-z]+/g, '')); // john.doe
Enter fullscreen mode Exit fullscreen mode

replaceAll()

  • replaceAll(searchString, newValue): is a method that returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.more details...
const slug = '5-html-tags-that-almost-nobody-knows';
// 5 html tags that almost nobody knows
console.log(slug.replaceAll('-', ' ')); 
// 5 html tags that almost nobody knows
console.log(slug.replaceAll(/-/g, ' ')); 
Enter fullscreen mode Exit fullscreen mode

search()

  • search(valueToSearch) : returns the position (index) of a specific value in a string, if the specific value does not exist in the string, it returns -1.
const quote = 'A dream does not become reality through magic; it takes sweat, determination, and hard work';
console.log(quote.search('magic')); // 40
console.log(quote.search(/life/g)); // -1
Enter fullscreen mode Exit fullscreen mode

trim()

  • trim() : delete whitespaces & tabs from the start & the end of a string
const inputValue = '  Aya   Bouchiha\t';
console.log(inputValue.trim()); // Aya   Bouchiha
Enter fullscreen mode Exit fullscreen mode

includes()

  • includes(value) : this method checks if a giving value exists in a string. if the value exists, It returns true, otherwise, It returns false
const address = 'Morocco, Rabat';
console.log(address.includes('Morocco'));// true
console.log(address.includes('morocco'));// false
console.log(address.includes('tanger')); // false
Enter fullscreen mode Exit fullscreen mode

toLowerCase()

  • toLowerCase() : this method returns a given string with lowercase letters.
const name = 'AYa BoUCHIha';
console.log(name.toLowerCase()) // aya bouchiha
Enter fullscreen mode Exit fullscreen mode

toUpperCase()

  • toUpperCase() : returns a given string with uppercase letters.
const name = 'AYa BoUCHIha';
console.log(name.toUpperCase()) // AYA BOUCHIHA
Enter fullscreen mode Exit fullscreen mode

toLocaleUpperCase()

  • toLocaleUpperCase(locals: optional) : returns a given string with uppercase letters according to locale-specific case mappings. It's the same thing with toLocaleLowerCase but this one returns the string with lowercase letters. more details
const turkishSentence = 'iskender kebap';
// ISKENDER KEBAP
console.log(turkishSentence.toLocaleUpperCase('en-us')); 
// İSKENDER KEBAP
console.log(turkishSentence.toLocaleUpperCase('tr')) 
Enter fullscreen mode Exit fullscreen mode

repeat()

  • repeat(n) : returns a string repeated n times.
const firstName = 'aya';
console.log(firstName.repeat(3)) // ayaayaaya
Enter fullscreen mode Exit fullscreen mode

slice()

const fullName = 'Aya Bouchiha';
console.log(fullName.slice()) // Aya Bouchiha
console.log(fullName.slice(0,3)) // Aya
console.log(fullName.slice(4,fullName.length)) // Bouchiha
Enter fullscreen mode Exit fullscreen mode

substr()

  • substr(startIndex, length=string.length) : returns a specific part of a string, starting at the specified index and extending for a given number of characters afterwards.
const fullName = 'Aya Bouchiha';
console.log(fullName.substr(0,3)) // Aya
console.log(fullName.substr(4,8)) // Bouchiha
Enter fullscreen mode Exit fullscreen mode

chartAt()

  • chartAt(index = 0) : this method returns the character at a giving index in a string. Note: 0 <= index < string.length
const product = 'laptop';
console.log(product.charAt(3)) // t
console.log(product.charAt(10)) // ''
product.charAt("this is a string!") // l
console.log(product.charAt()) // l
Enter fullscreen mode Exit fullscreen mode

charCodeAt()

  • charCodeAt(index): method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
const product = 'laptop';
console.log(`the character code of ${product.charAt(2)} is  ${product.charCodeAt(2)}`)
// the character code of p is 112
Enter fullscreen mode Exit fullscreen mode

startsWith()

  • startsWith(valueToSearch, startingIndex = 0) : returns true if a string starts with a giving value, otherwise It returns false;
const phoneNumber = '+212612342187';
console.log(phoneNumber.startsWith('+212')) // true
console.log(phoneNumber.startsWith('6',4)) // true
console.log(phoneNumber.startsWith('6',3)) // false
Enter fullscreen mode Exit fullscreen mode

endsWith()

  • endsWith(valueToSearch, length=string.length) : returns true if a string ends with a giving value, otherwise It returns false;
const address = 'tanger, Morocco';
console.log(address.endsWith('Morocco')); // true
console.log(address.endsWith('Canada')); // false

const gmail = 'developer.aya.b@gmail.com';
const isGmail = gmail.endsWith('@gmail', gmail.length - 4)
console.log(isGmail); // true
Enter fullscreen mode Exit fullscreen mode

fromCharCode()

  • fromCharCode(n1, n2,...) : converts a unicode number to a character.
console.log(String.fromCharCode(112)) // p
console.log(String.fromCharCode(105,106)) // ij
Enter fullscreen mode Exit fullscreen mode

indexOf()

  • indexOf(value, start=0) : returns the position of the first occurrence of a specified value in a string. If the value is not found, It returns -1.
const quote = "every day may not be good... but there's something good in every day";
console.log(quote.indexOf('good')); // 21
console.log(quote.indexOf('good',24)); // 51
Enter fullscreen mode Exit fullscreen mode

lastIndexOf()

  • lastIndexOf(value, start) : returns the position of the last occurrence of a specified value in a string. It searches the string from the end to the beginning, but returns the index s from the beginning, starting at position 0. If the value is not found, It returns -1.
const quote = "every day may not be good... but there's something good in every day";
console.log(quote.lastIndexOf('good')); // 51
console.log(quote.lastIndexOf('good',24)); // 21
Enter fullscreen mode Exit fullscreen mode

localeCompare()

  • localeCompare(stringToCompare, locales) : returns -1, 1, or 0 if the string comes before, after, or is equal the given string in sort order.more details
const word1 = 'feel';
const word2 = 'flee';
// returns -1
// because word1 comes before word2
console.log(word1.localeCompare(word2)) 
Enter fullscreen mode Exit fullscreen mode

valueOf()

  • valueOf() : returns the primitive value of a string.
const fName = new String('Aya');
const lName = 'Bouchiha';
console.log(fName); // [String: 'Aya']
console.log(fName.valueOf()); // Aya
console.log(lName.valueOf()); // Bouchiha
Enter fullscreen mode Exit fullscreen mode

toString()

  • toString() : returns a string representing the specified object.
const moroccanCity = new String('tanger');
console.log(moroccanCity); // [String: 'tanger']
console.log(moroccanCity.toString()) // tanger
Enter fullscreen mode Exit fullscreen mode

Summary

  • concat() : links together two strings or more.
  • match() : searchs a string for a match against a regular expression, and returns the matches as an Array.
  • matchAll(): returns an iterator of all results matching a string against a regular expression, including capturing groups.
  • split() : convert a string to an array by spliting it into substrings.
  • replace(), replaceAll() : return a new string with some or all matches of a pattern replaced by a replacement.
  • search() :returns the position of a specific value in a string
  • trim() :delete whitespaces & tabs from the start & the end of a string
  • includes() : checks if a giving value exists in a string
  • toLowerCase() : returns a given string with lowercase letters.
  • toUpperCase() : returns a given string with uppercase letters.
  • toLocaleLowerCase() : returns a given string with lowercase letters according to locale-specific case mappings.
  • toLocaleUpperCase() : returns a given string with uppercase letters according to locale-specific case mappings.
  • repeat() : repeat a string n times
  • slice(), substr(), substring() : extract a specific part of a string
  • chartAt() :returns the character at a giving index in a string.
  • charCodeAt() :returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
  • startsWith() : returns true if a string starts with a giving value, otherwise It returns false;
  • endsWith() :returns true if a string ends with a giving value, otherwise It returns false;
  • fromCharCode() : converts a unicode number to a character.
  • indexOf() : returns the position of the first occurrence of a specified value in a string.
  • toString() : returns a string representing the specified object.
  • lastIndexOf() :eturns the position of the last occurrence of a specified value in a string.
  • localeCompare() :returns -1, 1, or 0 if the string comes before, after, or is equal the given string in sort order.
  • valueOf() : returns the primitive value of a string.

to contact me:

References

Have an amazing day!

Top comments (0)