Appearance
正则算法题
本节目标:理解“正则算法题”的核心思路,并能把它用于实际开发或面试表达。
说明:原 OneNote 中有图片引用,但图片未包含在导出目录中;本页保留了可用的文字与代码内容。 将字符串中的字符
&、\<、\>、
"(双引号), 以及
'(单引号)转换为它们对应的 HTML 实体。
function convert(str) {
let reg = /[&<>"']/g;
let strFilter = function (matches) {
switch (matches) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case "'":
return ''';
default:
return '';
}
};
return str.replace(reg, strFilter);
}Spinal Tap Case 将字符串转换为 spinal case。Spinal case 是 all-lowercase-words-joined-by-dashes 这种形式的,也就是以连字符连接所有小写单词。
RegExpString.replace()
spinalCase("This Is Spinal Tap")应该返回 "this-is-spinal-tap"。 spinalCase("thisIsSpinalTap") 应该返回 "this-is-spinal-tap"。 spinalCase("The_Andy_Griffith_Show")应该返回 "the-andy-griffith-show"。 spinalCase("Teletubbies say Eh-oh") 应该返回 "teletubbies-say-eh-oh"。
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str.replace(/\s|_/g, '-').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}