常见输入处理/格式转换
字符串转数组
str1 = "[1, 21, 3]"
str2 = "[[1, 21, 3], [4, 5, 6], [7, 8, 9]]"
let jsonReady = str.trim().replace(/'/g, '"');
let arr = JSON.parse(jsonReady);
[ '1', '21', '3' ]
[ [ '1', '21', '3' ], [ '4', '5', '6' ], [ '7', '8', '9' ] ]
- 普通的多行字符串,数字之间用空格隔开(空格数量不固定)
"1 21 3
4 5 6
7 8 9 "
return str
.split(/\r?\n/)
.map(line => line.trim().split(/\s+/).map(String));
语法:
JSON.parse(text, function(key, value) {
// key: 当前的键
// value: 当前的值
return 处理后的值;
});
例 1:把所有数值翻倍
let str = '{"a": 1, "b": 2, "c": "hi"}';
let obj = JSON.parse(str, (key, value) =>
typeof value === "number" ? value * 2 : value
);
console.log(obj); // { a: 2, b: 4, c: 'hi' }
再复杂点就要用正则了
- 经典题目:实现字符串的trim()方法
String.prototype._trim = function () {
// this 就是字符串本身,直接在其上调用方法即可
return this.replace(/^\s+|\s+$/g, '');
};
1️⃣ 匹配基础题
- 判断字符串是否全是数字
/^\d+$/
- 判断字符串是否全是字母
/^[A-Za-z]+$/
- 判断字符串是否是合法邮箱
/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/
- 判断是否是手机号(中国)
/^1[3-9]\d{9}$/
2️⃣ 提取内容题
- 提取 HTML 标签中的内容
const str = "<p>Hello</p>";
str.match(/<p>(.*?)<\/p>/)[1]; // "Hello"
- 提取 URL 中的 query 参数
const url = "https://example.com?a=1&b=2";
url.match(/[\?&]([^=]+)=([^&]+)/g);
// ["?a=1", "&b=2"]
- 提取文本中的数字
const text = "价格是100元";
text.match(/\d+/g); // ["100"]
3️⃣ 替换/校验题
- 去掉字符串首尾空格
str.replace(/^\s+|\s+$/g, '');
- 把连续多个空格替换成一个
str.replace(/\s+/g, ' ');
- 把文本中的数字加前缀
str.replace(/\d+/g, n => 'ID' + n);
4️⃣ 高阶题(常考)
- 匹配 IPv4 地址
/^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.|$)){4}$/
- 匹配日期 YYYY-MM-DD
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
- 反向引用 + 分组
- 替换重复单词:
const str = "hello hello world";
str.replace(/\b(\w+)\s+\1\b/g, "$1"); // "hello world"
5️⃣ 思路总结
- 分组:用
()
捕获内容 - 量词:
*
/+
/?
/{n,m}
控制重复 - 边界:
^
/$
/\b
控制位置 - 字符集合:
[]
/[^]
控制范围 - 转义:
.
/\d
/\s
/\w
等
面试中往往不会考你记复杂正则公式,而是考你能快速拆解需求 → 用正则解决,比如“提取、校验、替换”。