JavaScript替换正则表达式空格和换行符

kiz8lqtg  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(92)

如何在javascript中替换空格和换行符以及附加的关闭代码;

function main(){
   var a = 'hello'
   console.log(a)
}

console.log(main.toString().replace(/[\n ]/g,''))

输出量

functionmain(){vara='hello'console.log(a)}

我想要

function main(){var a='hello';console.log(a);}
hivapdat

hivapdat1#

也许这是正确的

function removeSpaces(str){
        str = str.replace(/[\n]/g,';')
    let res = str.replace(/[\n ;]/g,(e, i)=>{
       switch(e){
         case ';':
           if(!'{:['.includes(str.substr(0, i).slice(-1))){
             return ';'
           }
        default:
          let arr = str.substr(0, i).split(' ')
          let lastArr = arr[arr.length - 1]
          // need space code
          if(['function','var','let','const'].includes(lastArr)){
             return ' '
          }
          return ''
        }
     })
    return res;
}
function main(){
   var a = 'hello'
   console.log(a)
}

let str = main.toString()
console.log(str.replace(/[\n ]/g,''))
let res = removeSpaces(str)
console.log(res) // function main(){var a='hello';console.log(a);}
wlwcrazw

wlwcrazw2#

根据您的要求,我认为regex可以完成这项工作:

/(?:(?<![\{\}])[\n]|([\{\}\;])(\n)|\b\s\B|\B\s\b|\B\s\B)/g

1-第一部分:

(?<![\{\}])[\n] -> matches ending of statements without ;

2-第二部分:

([\{\}\;])(\n) -> matches newlines after { or } or ;

3-第三部分:

\b\s\B|\B\s\b|\B\s\B ->match white spaces
function main() {
    var a = "hello"
    console.log(a)
    return 1;
  }
  
const result = main.toString().replaceAll(
  /(?:(?<![\{\}])[\n]|([\{\}\;])(\n)|\b\s\B|\B\s\b|\B\s\B)/g,
  function (match, p1) {
    if (match === "\n") return ";";
    if (match === " ") return "";
    return p1;
  }
);

console.log(result);

相关问题