- 获取要被处理的字符串,通过则表达式匹配出大括号内容
- 对大括号内容进行处理,在每行开头加上空格,可以使用 string.replace() 方法,将定符号替换为带空格的符号
- 对于嵌套的大括号,采用递归处理的方式,重复上述步骤即可
代码如下:
function formatString(input) {
let result = input.replace(/{([^{}]+)}/g, function(match, p1) {
const innerContent = p1.replace(/\n\s*/g, function(metaContent) {
return '\n ' + metaContent.trim(); // 每一行增加四个空格
});
return '{\n ' + innerContent + '\n}'; // 大括号包裹的内容缩进
});
if (result !== input) { // 需要递归处理
return formatString(result);
}
return result;
}
这个示例中,我们定义了一个 formatString 函数,输入需要被处理的字符串,根据正则表达式匹配出所有大括号内容。之后,我们对于每个大括号内容都使用replace函数,将内部换行符后面的内容进行缩进并返回新的字符串,最后再对原始字符串进行修改。函数还包含一个递归调用,以处理字符串中存在嵌套大括号的情况。
运用如下:
const input = "function myFunc() {\n const a = {name: 'Alice', age:{\n year:10,\n class:'A'\n} };\n}";
console.log(formatString(input));
输出结果如下:
function myFunc() {
const a = {
name: 'Alice',
age:{
year:10,
class:'A'
}
};
}