Regularly intercept/replace a string between two characters

regular expression

  • A regular expression used to match strings

Create a regular object

  • Constructor
    • var reg = new RegExp(regular expression, matching pattern);
    new RegExp(pattern,attributes);
    参数:参数pattern是一个字符串,指定了正则表达式的模式;
    参数attributes是一个可选的参数,包含属性 g(globle全局匹配),i(忽略大小写),m(多行匹配)
  • literal
    • var reg = /regular rule/matching pattern;

Call matching method

  • test most commonly uses a regular object to match a certain string
    • If the match is successful, get true, otherwise false
    • Regular object.test(string)
    例:匹配字符串中出出现连续的三个小写a
    var reg = new RegExp(/a{3}/);
    console.log(reg.test("aaac")); //true
    console.log(reg.test("baaab"));//true
    console.log(reg.test("aa"));//false
    console.log(reg.test("AAA"));//false
  • match is used to match a certain string
    • String.match(regular expression)
    • Return value: array – containing the matched string and the index of the matched original string
    例:匹配字符串中是否包含连续的三个小写a
    console.log("aaabcdefaaaghjiy".match(/a{3}/));
  • exec
    • Used to match strings
    • Regular object.exec(string) return value is the same as match

Intercept/replace a string between two characters

const str = '/detail/page-1.html'
// 获取
str.match(/page-(\S*).html/)[1]
// 替换
str.replace(/(?<=page-).*?(?=.html)/, 2)

Guess you like

Origin blog.csdn.net/kiscon/article/details/119856593