Substrings substitution using replaceAll()
replaceAll (pattern, replacement)
- pattern: A string or an object or a Regular Expression with the global (g) flag
- replacement: Be a string or a function. For functions, it can be invoked for every match and its return value as replacement text. Various replacement patterns are supported.
This method will pass a string after modification as its return type and not mutate the initial one. Hence, you need to assign your target string to the returned value.
Our code snippet using this method should be as such:
let mystr = "apple, pen, ink, coal"; myst = mystr.replaceAll (',',""); console.log(mystr);
apple pen ink coal
In this example, we replace all commas with empty substrings. Whatever replacement is to be passed in the method is at your disposal.
Using Regular Expression with replace()
Compared to the previous replaceAll(), this method lacks the apparent word “All” in its function name. Up to what it’s called, when you pass a substring to replace(), only the first instance that matches the pattern is replaced.
// passing a substring let str = "checks,the,first,instance"; str = str.replace('-', ' '); console.log(str);
To make replace() checks for all occurrences, we recommend using Regular Expression.
Regular Expressions can be created either by literal notations or constructors.
// literal notations const pttrn = /,/g; // regular expression constructors const pttrn = new RegExp(/,/, 'g');
Flags that specify the search of these expressions should be attached at the end of literal notations or the second argument of
Each Regular Expression above will give the same output:
Str = str.replace (pttrn," ");
checks the first instance
Implementing conversion between a string and an array
In this approach, we will attempt to divide a string into an array of substrings by negating its commas. Next, these substrings will be assembled into a new string following the exact order given a separator.
- Separator: (optional) A string or an object, typically a Regular Expression
- Limit: (optional) A non-negative integer indicating the number of substrings to include in the to-be-returned array. All leftover text after the limit will be removed.
- An array may contain fewer members than limit
- If limit = 0 , split() returns
- The separator is optional. This parameter specifies what will separate each pair of elements in the array. If empty, it will automatically use commas.
We will execute an example below on how to remove all commas from a string:
let str = "no, commas, in, this, string"; str = str.split(/,/).join(""); console.log(str);
no commas in this string
Maybe you are interested:
Name of the university: UTC