前端js面试题--从字符串中删除删除注释代码

发布于:2024-05-10 ⋅ 阅读:(26) ⋅ 点赞:(0)

问题:从字符串中删除删除注释代码

描述:

solution(weex,rex # and react\nflutter\nnative ssss !hybrid app, [#, !])
写一个solution函数清除后面参数数组里面的字符串
打印效果
在这里插入图片描述

代码1

思路:

  1. 将字符全凡是有去掉标志符号的全部添加\n进行换行;
  2. 进行循环过滤出没有标识的数组;
  3. 将数组转换成字符串。
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

思路:

  1. 将字符以换行转数字;
  2. 进行循环将里面包含需要删除字符重新定义;
  3. 返回所定义的值,拿到新数组;
  4. 进行对数组转换字符串;
    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

思路:

  1. 将字符全凡是有去掉标志符号的全部添加\n进行换行;
  2. 通过双重循环进行重新赋值给对象;
  3. 进行对对象循二次排除;
  4. 转换成字符串;
  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");
 }

网站公告

今日签到

点亮在社区的每一天
去签到