String - patrickcole/learning GitHub Wiki
String
String.prototype.matchAll
- The regular expression used inside the
.matchAll
method must have a global flag set - Returns:
RegExpStringInterator
Object
const regex = /\b(apple)+\b/g;
const fruits = "pear, apple, banana, apple";
let matches = [...fruits.matchAll(regex)];
matches.forEach( result => console.dir(result) );
/*
// [
// 'apple',
// 'apple',
// index: 6,
// input: 'pear, apple, banana, apple, orange, apple',
// groups: undefined
// ],
// [
// 'apple',
// 'apple',
// index: 21,
// input: 'pear, apple, banana, apple, orange, apple',
// groups: undefined
// ]
*/
String.prototype.replaceAll
- Coming in ES2021
- Allows for global string replacement rather than having to use a RegEx
const phrase = "The cat found the rhatt. The rhatt was looking for cheese!";
// instead of having to do this:
const usingReplace = phrase.replace(/rhatt/g, `rat`);
// you can now do this:
const usingReplaceAll = phrase.replaceAll(`rhatt`, `rat`);
Easier to understand and no knowledge of Regular Expressions (RegEx) is required!
String.prototype.slice
- Arguments are: (startIndex, endIndex)
- If both arguments are equal, returns empty string
- If both arguments are greater than length, returns empty string
- If startIndex > endIndex, returns empty string
- If startIndex is a negative number, returns string *starting from end of string
let text = "we are learning";
console.log(text.slice(-8));
// => "learning"
String.prototype.substr
- Arguments are: (startIndex, length)
let text = "we are learning";
console.log(text.substr(0,6));
// => "we are"
// can still string from the right:
console.log(text.substr(-3));
// => "ing"
// will start from right and move left number of characters
// provided in startIndex and continue returning until it
// reaches the length amount or end of string:
console.log(text.substr(-3,1));
// => "i"
// it started at the right and only provided one character "i"
// start 3 characters from right and provide a length of 2:
console.log(text.substr(-3,2));
// => "in";
String.prototype.substring
- Arguments are: (startIndex, endIndex)
- If startIndex === endIndex, will return empty string
- If startIndex and endIndex are greater than length of the string, returns empty string
- If startIndex > endIndex, the two arguments are swapped
// startIndex and endIndex provided:
let text = "we are learning";
console.log(text.substring(0,6))
// => "we are"
// just startIndex provided:
console.log(text.substring(6));
// => " learning"
// notice the extra space character before learning;
// startIndex is greater than endIndex:
console.log(text.substring(12,0));
// => "we are learn"
// this effectively means the same as:
// text.substring(0,12);