const regForTrim = /^\s*|\s*$/g;
const spaceStr = '123 456 789 ';
console.log(`去除字符串两边的空格:${
spaceStr.replace(regForTrim, '')
}`);
const str = 'this is a dog';
const regForLocaleUpperCase = /(?:^|\s)(\w)/g;
console.log(`首字母转换为大写:${
str.replace(regForLocaleUpperCase, match => match.toLocaleUpperCase())
}`)
const camelizeStr = 'moz transform';
const regForcamelize = /(?:^|\s|-|_)+(\w)/g;;
console.log(`驼峰化:${
camelizeStr.replace(regForcamelize, (match, $1) => $1.toLocaleUpperCase())
}`)
const escapeChars = {
'¢': 'cent',
'£': 'pound',
'¥': 'yen',
'€': 'euro',
'©': 'copy',
'®': 'reg',
'<': 'lt',
'>': 'gt',
'"': 'quot',
'&': 'amp',
'\'': '#39'
};
const htmlEntities = Object.entries(escapeChars).reduce((pre, cur) => {
const[left, right] = cur;
pre[right] = left;
return pre;
},
{})
const escapeHTML = (str) => {
return str.replace(new RegExp('[' + Object.keys(escapeChars).join('') + ']', 'g'), (match) => `\$${
escapeChars[match]
};`)
}
const unescapeHTML = str => {
return str.replace(/\$([^;]+);/g, (match, $1) => htmlEntities[$1])
}
console.log(`html转义:${escapeHTML('<div>¥</div>')}`);
console.log(`html反转义:${unescapeHTML('$lt;div$gt;$yen;$lt;/div$gt;')}`);
console