Skip to content
Go back

regexp example

Published:  at  05:28 PM

Replacement of matched content in regexp

The $ selector is a flag or option used during replacement, but if it is used within the regular expression itself, it needs to be escaped with a backslash.

Group capturing uses parentheses to group data. The selected groups start from No.1.

// $1, $2 represent the first and second groups, here it is used to swap the positions of two groups.
"guizhun tu".replace(/(\w+)\s(\w+)/, "$2 $1"); //tu guizhun

\ used to escape special characters in regular expressions.

var s = "aaabbbcccaaabbbaaa";
var a = s.split("").sort().join(""); //"aaaaaaaaabbbbbbccc"
var ans = a.match(/(\w)\1+/g); // \1 represent the first matched group content, here (\w)\1 means that the same character is repeated more than once.

ans.sort(function (a, b) {
  return a.length - b.length;
});
console.log("ans is : " + ans[ans.length - 1]);

Trim method simulation

// 1. Extract the key character in the middle, using group reference
const trim1 = str => {
  return str.replace(/^\s*(.*?)\s*$/, "$1");
};
// 2. remove leading and trailing whitespace characters
const trim2 = str => {
  return str.replace(/^\s*|\s*$/g, "");
};

Capitalize the first letter

const titleize = str => {
  return str.toLowerCase().replace(/(?:^|\s)\w/g, c => c.toUpperCase());
};
console.log(titleize("my name is epeli")); // My Name Is Epeli
// 拓展,横向转驼峰,例如base-act-tab => baseActTab
"base-act-tab".replace(/(?:-)(\w)/g, ($0, $1) => $1.toUpperCase()); // baseActTab

HTML escaping rules

const escapeHTML = (str) => {
    const escapeChars = {
    '<': 'lt',
    '>': 'gt',
    '"': 'quot',
    ''''#39',
    '&': 'amp'
  }
  
  let regexp = new RegExp(`[${Object.keys(escapeChars).join('')}]`, 'g') // 为了得到字符组[<>"'&]
    
    return str.replace(regexp, (c) => `&${escapeChars[ c ]};`)
}

console.logescapeHTML('<div>Blah blah blah</div>')) // &lt;div&gt;Blah blah blah&lt;/div&gt;

Unescape

const unescapseHTML = str => {
  const htmlEntities = {
    nbsp: " ",
    lt: "<",
    gt: ">",
    quot: '"',
    amp: "&",
    apos: "'",
  };
  return str.replace(/&([^;]+);/g, ($0, $1) => {
    return htmlEntities[$1] || "";
  });
};

console.log(unescapseHTML("&lt;div&gt;Blah blah blah&lt;/div&gt;")); // <div>Blah blah blah</div>

Match paired tags

let reg = /<([^>]+)>.*?</\1>/g

console.log(reg.test('<title>regular expression</title>')) // true
console.log(reg.test('<p>laoyao bye bye</div>')) // false


Previous Post
编程中常用符号的英文怎么读
Next Post
强大的正则表达式