简体   繁体   中英

Line breaks in a string

Script #1:

<textarea></textarea>

$('textarea').each(function() {
  var $placeholder = "First line\nSecond one";
  console.log('[function] shikamo__edit_placholder, data-placeholder: ' + $placeholder);

  $(this).attr('value', $placeholder);
  $(this).focus(function(){
      if($(this).val() == $placeholder){
          // reset the value only if it equals the initial one    
          $(this).attr('value', '');
      }
  });
  $(this).blur(function(){
      if($(this).val() == ''){
          $(this).attr('value', $placeholder);
      }    
  });
  // remove the focus, if it is on by default
  $(this).blur();
});

returns

<textarea>First line
Second one</textarea>

Script #2:

<textarea data-placeholder="First line\nSecond one"></textarea>

$('textarea').each(function() {
  var $placeholder = $(this).attr('data-placeholder');
  console.log('[function] shikamo__edit_placholder, data-placeholder: ' + $placeholder);

  $(this).attr('value', $placeholder);
  $(this).focus(function(){
      if($(this).val() == $placeholder){
          // reset the value only if it equals the initial one    
          $(this).attr('value', '');
      }
  });
  $(this).blur(function(){
      if($(this).val() == ''){
          $(this).attr('value', $placeholder);
      }    
  });
  // remove the focus, if it is on by default
  $(this).blur();
});

returns

<textarea data-placeholder="First line\nSecond one">First line\nSecond one</textarea>

How can I get the same result with a line break

<textarea data-placeholder="First line\nSecond one">First line
Second one</textarea>

from Script #2?

using @Ishita's answer

$(this).attr('value', ($placeholder.replace(/\\n/g, "\n")));

EDIT

it's because when you read a property from placeholder attribute it's seen not as a line break but as a regular \\n string. if you change that string back into line break, you are at home.

Use

<br/> instead of /n 

Or if you are rendering a string,

replace /n with <br/>
// this is code for string replacement
replace(/\n/g, "<br />");

Basically, write this code

  $(this).attr('value', ($placeholder.replace(/\n/g, "<br />")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM