String and regular related methods

split()

  • You can split a string into an array
  • A regular expression can be used as a parameter in the method, so that the method will split the string according to the regular expression
  • Split the string according to any letter and ignore the case
    var result = str.split(/[Az]/)
  • This method does not set the global matching mode, it will also split

//Split the string according to any letter, and ignore the case
var result = str.split(/[Az]/);
console.log(result);
console.log(result.length);

search()

  • Can search for the specified content in the string
  • If the specified content is searched, the index of the first occurrence will be returned. If no search is found, -1 will be returned
  • It will accept a regular expression as a parameter, and then retrieve the string according to the regular expression
  • Global matching mode is not accepted, even if it is set to global matching mode, it will be ignored

//search()
//You can search for the specified content in the string
var str = "hello abc hello abc"
result = str.search("abc");
console.log(result); //return to the first time Index of occurrence

//Search whether the string contains abc or sec or afc
var str = "hello abc hello aec afc";
result = str.search(/a[bef]c/);
console.log(result); //return One-time index

match()

  • According to regular expressions, the qualified content can be extracted from a string
  • By default, match() will only find the first content that meets the requirements. After finding it, it will stop searching. You can set the regular expression to the global matching mode, so that all the content will be matched.
  • You can set multiple matching modes for regular expressions, and the order does not matter
  • match() will encapsulate the matched content into an array and return, even if only one result is found

//match() extracts the content that meets the requirements
var str="1a2b3c4d5e6f7A8B9C";
result = str.match(/[az]/ig) //i ignore case g global matching mode
console.log(result);
console .log(Array.isArray(result)); //return true

replace()

  • You can replace the specified content in the string with new content
  • Parameters:
    1. Content to be replaced
    2. New content
  • Only the first one will be replaced by default, and the global matching mode needs to be set

//replace() can replace the specified content in the string with new content
var str="1a2b3c4d5e6af7A8aB9C";
var result = str.replace(/a/ig,"@_@");
//delete letters
var result = str.replace(/[az]/ig,"");
console.log(result);

Guess you like

Origin blog.csdn.net/weixin_48769418/article/details/111675532