The goal of this tutorial is to provide an understanding of how to use regular expressions to effectively replace and split text in web development. By the end of this tutorial, you will have learned:
replace()
function to modify textsplit()
function to divide textPrerequisites:
- Basic understanding of web development
- Familiarity with JavaScript
Regular Expressions
A regular expression (regex) is a sequence of characters that forms a search pattern. Regex can be used to check if a string contains the specified search pattern.
The replace()
function
In JavaScript, replace()
is a string function that allows us to replace occurrences of a specified value.
let str = "Hello World!";
let res = str.replace("World", "Universe");
In this example, str.replace("World", "Universe")
will replace the first occurrence of "World" with "Universe".
The split()
function
The split()
function is used to split a string into an array of substrings and returns the new array.
let str = "How are you doing today?";
let res = str.split(" ");
In this example, str.split(" ")
will split the string every time it encounters a space, and return an array of the words in the string.
Example 1: Using replace()
let str = "I love apples, apples are my favorite fruit";
let result = str.replace(/apples/g, "oranges");
console.log(result);
In this example, the regular expression /apples/g
is used to replace all occurrences of the word "apples" with "oranges". The g
after the regular expression is used to perform a global match (find all matches rather than stopping after the first match).
Example 2: Using split()
let str = "How are you doing today?";
let result = str.split(" ");
console.log(result);
In this example, the str.split(" ")
method splits the string every time it encounters a space. The output will be an array containing each word from the sentence.
In this tutorial, we've covered:
replace()
function to modify textsplit()
function to divide textNext, you could learn more advanced uses of regular expressions, such as using the test()
method and the match()
method.
let str = "bad things are not always bad";
let result = str.replace(/bad/g, "good");
console.log(result);
let str = "How are you doing today?";
let result = str.split(" ");
console.log(result);
function replaceSecondOccurrence(str, word, newWord) {
let regex = new RegExp(`(${word}.*?){2}`, 'i');
return str.replace(regex, function(match) {
return match.replace(word, newWord);
});
}
console.log(replaceSecondOccurrence("It is what it is", "it", "it's"));
In this solution, we first construct a regular expression that matches the second occurrence of the word. Then we replace this match with the new word. This only changes the second occurrence, leaving the rest of the string untouched.