Omu
Omu

Reputation: 71288

trying to replace all \n inside textarea to '\n (4 spaces) ' and viceversa but only one \n is found

here's the link where I'm trying this:

http://jsbin.com/ajirim/2/edit#source

the js code:

$(function(){
    $('button').click(dao);
    });

   function dao()            {
   var x = $('textarea').val();

   if(x.substring(0,4) == '    ')
   {
      x = x.replace('\n    ','\n').substr(4);
   }
   else
   {
      x = '    '+ x.replace('\n', '\n    ');
   }

   $('textarea').val(x);
}

Upvotes: 0

Views: 71

Answers (1)

duri
duri

Reputation: 15351

You're missing the g flag:

   if(x.substring(0,4) == '    ')
   {
      x = x.replace(/\n {4}/g,'\n').substr(4);
   }
   else
   {
      x = '    '+ x.replace(/\n/g, '\n    ');
   }

Upvotes: 4

Related Questions