Methods that may be used in regular expressions

Posted Jun 29, 20204 min read

This article mainly explains the methods that will be used

First, let's start with a string of strings:

 let content ='gabgAjklbgadlkjgbajkdgbAjldgbadg'

The first is a simple method that does not require the use of regular

indexOf

If it is a simple match str or intercept the matched text, I will use str.indexOf(searchvalue,[fromindex]), the result will return the index of the first value, if there is no match, it will return -1 ,
At present, it is a little more complicated to use in two cases. It is that the g global match and i in the regular case are not case sensitive. If only the matching case is judged, the str and searchvalue are all converted to toLowerCase() lowercase To make judgments,
If it is only used to find whether a single continuous character exists in the target str, it is recommended to use indexOf(),

//toLowerCase() is case sensitive
content.toLowerCase().indexOf('aj') //4
//If you want to get the number of all matches
let currentIndex = content.toLocaleLowerCase().indexOf('aj');
let indexArr = [];
for(var i = 0;i<content.length;i++) {
  if(currentIndex!=-1) {
    indexArr.push(currentIndex);
    currentIndex = content.toLocaleLowerCase().indexOf('aj',currentIndex+1)
  }
}
console.log(indexArr); //[4, 17, 23]

includes

There is also a good method in es6:str.includes(searchvalue,[fromIndex])
The includes() method returns a Boolean value, includes() can also judge undefined and NaN

content.toLowerCase().includes('aj') //true

Uncommon exec()

The exec() method performs a search match on a specified string. Returns a result array or null.
Usage:regexObj.exec(str) returns null if there is no match, returns an array if there is a value
Experience:The first parameter of the returned array is the first string matched to the regular, the second is the index of the first, the third is your regularized str

console.log(/aj/i.exec(content))
//["Aj", index:4, input:"gabgAjklbgadlkjgbajkdgbAjldgbadg", groups:undefined]

A simple test for matching method test()

The test() method performs a search to see if the regular expression matches the specified string. Returns true or false
Usage:regexObj.test(str)
If the regular expression has a global flag set, the execution of test() will change the lastIndex property of the regular expression. Continuous execution of the test() method, subsequent executions will match the string from lastIndex,(exec() also changes the value of the lastIndex property of the regular itself).@1
Experience:This test is actually similar to indexOf. It is used to determine whether it is convenient.
Conclusion:simple and easy to use, only used to judge whether it matches

console.log(/aj/ig.test(content)); //true

@1

var regex = /aj/ig;
console.log(regex.test(content)); //true
console.log(regex.test(content)); //true
console.log(regex.test(content)); //true
console.log(regex.test(content)); //false

The best is here:match()

The match() method retrieves the result of a string matching regular expression.
Usage:str.match(regexp) Note that unlike the first two, match is a string method and the first two are RegExp methods
If the g flag is used, all results that match the full regular expression will be returned; if g is not used, the returned result is the same as exec

console.log(content.match(/aj/ig));
//["Aj", "aj", "Aj"]

String method search() that returns boolean

search() is similar to test(), but this is a string method
Usage:str.search(regexp)
If the match is successful, search() returns the index of the first match of the regular expression in the string; otherwise, it returns -1.
Similar to the regular expression test() method.

console.log(content.search(/aj/ig));
//4

Replace() the fields matched by the regular match

The replace() method returns a new string after replacing some or all matching patterns with replacement values.
Syntax:str.replace(regexp|substr, newSubStr|function)
regexp:regular expression to find what needs to be replaced
substr:a string to be replaced. It is treated as an entire string, not a regular expression. Only the first match will be replaced.
newSubStr:Used to replace the first part of the string in the original string matching part. Some special variable names can be interpolated into this string. For details, see https://developer.mozilla.org...
function:A function used to create a new substring. The return value of this function will replace the result of the first parameter match.
Summary:Replace the content of the first parameter matched by the string with the content of the second parameter and return a new string, and if the first parameter is a string, only the first matched content.
Note that a part or all matches the new string replaced by the alternative pattern. Did not change the original string.

//Give a written replacement function for highlighting
function highLightKeyword(txt, searchValue) {
  if(!txt) return''; //txt is the string to be replaced
  if(!searchValue) return''; //searchValue is the content that needs to be matched
  const keywords = searchValue.split(''); //Divide all words into single words to form an array
  for(const keyword of keywords) {
    txt = txt.replace(new RegExp(`(${keyword})`,'ig'), `<strong>$1</strong>`);
  }
  return txt;
}