This is the 20th day of my participation in the Genwen Challenge

The business scenario

In actual business development, there are usually two requirements for string substitution:

  1. Replaces the specified text
  2. Replaces text in a particular format

In addition, it also extends a specified number of substitutions, such as replacing only the first occurrence of the so-and-so text

In Java, there are two methods: replace and replaceAll

There are also various toolkits (e.g. Hutool/Apache, etc.)

So how does JavaScript work?

plan

The replace method

In JavaScript, a string has only one replace method

It replaces only the first occurrence of a character, just like in Java:

let test = 'YesOrYes';
console.log(test.replace('Yes'.'No'));
// NoOrYes
Copy the code

So if I want to replace all of them, do I need to do a manual loop?

The answer is clearly no, in fact replace supports all replacements, depending on the type of the first argument

When the argument is regular, all conforming contents of the string are replaced, and the code can be modified to look like this:

let test = 'YesOrYes';
let regexp = new RegExp('Yes'.'g')
console.log(test.replace(regexp, 'No'));
// NoOrNo
Copy the code

There are two things to note about using regular expressions:

  1. When the first variable is in regular format, for example/(\w+)\s(\w+)/, the second parameter must be ignored
  2. When the second variable is a string, the second argument supports G/I /m, representing global/case-sensitive/multi-line matching, respectively

We are now ready to do global substitution, but it is not very elegant to create a regular object every time

Add methods to String

The advantage of JavaScript over Java, of course, is that you can customize a lot of things.

I’m sure many of you have been exposed to prototype concepts during the development process.

String.prototype.replaceAll = function(oldVal, newVal) { 
    return this.replace(new RegExp(oldVal, 'g'), newVal); 
}

let test = 'YesOrYes';
console.log(test.replaceAll('Yes'.'No');
// NoOrNo
Copy the code