The syntax is therefore the following: string.replace (value, newValue).
Then the method accepts two mandatory parameters, the first value representing the value to search for in the string and which will subsequently be replaced by the second parameter, newValue.
In this first example we will replace one word with another.
Here is a possible implementation:
var sentence = 'coding since high school'; var sentenceChange = sentence.replace('high','primary'); console.log(sentenceChange);
In this way, if there are more occurrences, only the first one it encounters will be replaced. If we want to replace them all we can use the global operators.
This operator is used in conjunction with regular expressions which have the following syntax / pattern / modifiers. Then we enclose the value to be replaced in / and then add the modifier, in our case g.
Attention g is case-sensitive, so using this modifier does not substitute words that are not case-sensitive.
var sentence = 'Coding since high school. In first grade high school and second grade High school '; var sentenceChange = sentence.replace(/high/g,'primary'); console.log(sentenceChange);
In this case you will get this result: Coding since primary school. In first grade high school and second grade primary school.
So it did not replace Superiore as it has a capital letter.
You can use the global operator g with i, where i is a modifier as it modifies the search so that it is not case sensitive.
So here’s an example:
var sentence = 'Coding since high school. In first grade HIGH school and second grade high school '; var sentenceChange = sentence.replace(/high/gi,'primary'); console.log(sentenceChange);
In this example, all the terms ‘High’ will be replaced, regardless of how they are written.