问题:从字符串中删除删除注释代码
描述:
solution(weex,rex # and react\nflutter\nnative ssss !hybrid app
, [#
, !
])
写一个solution函数清除后面参数数组里面的字符串
打印效果
代码1
思路:
- 将字符全凡是有去掉标志符号的全部添加\n进行换行;
- 进行循环过滤出没有标识的数组;
- 将数组转换成字符串。
const solution = (str, arr) => {
arr.forEach(item => {
str = str.replaceAll(item, `\n${item}`);
});
const newArr = str.split(`\n`).filter(item => {
return !arr.includes(item[0]);
});
return newArr.join(`\n`);
}
console.log(solution(`weex,rex # and react\nflutter\nnative ssss !hybrid app`, [`#`, `!`]))
代码2
思路:
- 将字符以换行转数字;
- 进行循环将里面包含需要删除字符重新定义;
- 返回所定义的值,拿到新数组;
- 进行对数组转换字符串;
let result = solution("weex, rex # and react\nflutter\nnative !hybrid app", [
"#",
"!",
]);
function solution(str, arr) {
const newList = str.split('\n')
let newFilter = newList.map(e => {
arr.forEach(item => {
e.indexOf(item) != -1 ? e = e.split(item)[0].trim() : e
});
return e
})
return newFilter.join("\n")
}
console.log(result);
代码3
思路:
- 将字符全凡是有去掉标志符号的全部添加\n进行换行;
- 通过双重循环进行重新赋值给对象;
- 进行对对象循二次排除;
- 转换成字符串;
let result = solution("weex, rex # and react\nflutter\nnative !hybrid app", [
"#",
"!",
]);
function solution(str, arr) {
let a = str.split("\n");
let b = {};
a.forEach((item, index) => {
arr.forEach((res) => {
b[index] = item.split(res)[0].trim();
});
});
for (const key in b) {
arr.forEach((res) => {
b[key] = b[key].split(res)[0].trim();
});
}
return Object.values(b).join("\n");
}