skip to Main Content

how to replace spaces and newlines together with additional closing code ; in javascript?

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

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

output

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

I want

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

2

Answers


  1. Chosen as BEST ANSWER

    maybe this is correct

    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);}


  2. Based on your requirements, I think this regex can do the job:

    /(?:(?<![{}])[n]|([{};])(n)|bsB|Bsb|BsB)/g
    

    1- part one :

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

    2- part two:

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

    3- part three:

     bsB|Bsb|BsB ->match white spaces
    
    function main() {
        var a = "hello"
        console.log(a)
        return 1;
      }
      
    const result = main.toString().replaceAll(
      /(?:(?<![{}])[n]|([{};])(n)|bsB|Bsb|BsB)/g,
      function (match, p1) {
        if (match === "n") return ";";
        if (match === " ") return "";
        return p1;
      }
    );
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search