admin管理员组

文章数量:1389797

i would like to replace the space and line break in a textarea, if the input is

________________________________________
i am a 
fat

boy zzz
________________________________________

the result should be

i<sp>am<sp>a<br>fat<br><br>boy<sp>zzz

where space is replaced by <sp> and newline is replaced with <br>.

The space replacement is successfully done, but i failed when i try to replace new line with <br> (i tried 3-4 different methods but none of them can make it)

it would be grateful if anyone have idea? thanks in advance

The code is as follows

<!DOCTYPE html>
<html>
<body>

<textarea id="txtArea" rows="10" cols="70">i am fat boy </textarea>

<input type="text" id="StringTextBox" value="" >

<p id="demo"> </p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction() {
    var str = document.getElementById("txtArea").value; 

  var res = str.split(' ').join('&lt'+"sp"+'&gt');

    document.getElementById("demo").innerHTML = res;

}
</script>

</body>
</html>

i would like to replace the space and line break in a textarea, if the input is

________________________________________
i am a 
fat

boy zzz
________________________________________

the result should be

i<sp>am<sp>a<br>fat<br><br>boy<sp>zzz

where space is replaced by <sp> and newline is replaced with <br>.

The space replacement is successfully done, but i failed when i try to replace new line with <br> (i tried 3-4 different methods but none of them can make it)

it would be grateful if anyone have idea? thanks in advance

The code is as follows

<!DOCTYPE html>
<html>
<body>

<textarea id="txtArea" rows="10" cols="70">i am fat boy </textarea>

<input type="text" id="StringTextBox" value="" >

<p id="demo"> </p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction() {
    var str = document.getElementById("txtArea").value; 

  var res = str.split(' ').join('&lt'+"sp"+'&gt');

    document.getElementById("demo").innerHTML = res;

}
</script>

</body>
</html>
Share Improve this question asked Mar 16, 2015 at 15:41 Kan Lam TseKan Lam Tse 411 silver badge3 bronze badges 3
  • 1 You should give what you tried. Just notice that there is different line break depending on the OS. (\r , \n , ...) – Michael Laffargue Commented Mar 16, 2015 at 15:44
  • possible duplicate of How to replace \n with <br /> in JavaScript? – Rick S Commented Mar 16, 2015 at 15:45
  • str.replace(/(\S)/g,"<sp>").replace(/(\r\n|\n|\r)/g,"<br>") – Deepak David Commented Mar 16, 2015 at 15:51
Add a ment  | 

3 Answers 3

Reset to default 4

I wouldn't use split and join for this at all, just direct replacement. Note that different OSs (and even different browsers on the same OS) use different characters for line breaks, so to cover your bases you'll probably want an alternation:

str = str.replace(/(?:\r|\n|\r\n)/g, '<br>');

That will replace each standalone \r, a standalone \n, or a \r\n right next to each other with <br>.

And of course, we bine that with .replace(/ /g, '<sp>') to do the spaces:

str = str.replace(/ /g, '<sp>').replace(/(?:\r|\n|\r\n)/g, '<br>');

Gratuitous live example:

var originals = [
  "i am a\nfat\n\nboy zzz",
  "i am a\rfat\r\rboy zzz",
  "i am a\r\nfat\r\n\r\nboy zzz"
];
  
originals.forEach(function(str) {
  str = str.replace(/ /g, '<sp>').replace(/(?:\r|\n|\r\n)/g, '<br>');
  snippet.log(str);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange./a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

If it were a really big string then taking two passes through it (two calls to replace) might not be ideal. In that unlikely case, we could bine things into a single replace using a callback function:

str = str.replace(/(?: |\r|\n|\r\n)/g, function(m) {
    return m === " " ? "<sp>" : "<br>";
});

Live examples:

var originals = [
  "i am a\nfat\n\nboy zzz",
  "i am a\rfat\r\rboy zzz",
  "i am a\r\nfat\r\n\r\nboy zzz"
];
  
originals.forEach(function(str) {
  str = str.replace(/(?: |\r|\n|\r\n)/g, function(m) {
      return m === " " ? "<sp>" : "<br>";
  });
  snippet.log(str);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange./a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

But in the normal case of a reasonably-sized string, two calls to replace with direct replacements is probably better than a single call with a callback function.

You can do it with String.prototype.replace in one go by passing a function as the second parameter

var str = 'foo bar\nbaz';

str = str.replace(/(\r\n|\n)|(\s)/g, function ($0, $1, $2) {
    return ($2 && '&lt;sp&gt;') || '&lt;br&gt;'
});
// "foo&lt;sp&gt;bar&lt;br&gt;baz"

Should replace as you type :)

[].forEach.call(document.getElementsByTagName("textarea"), function(textarea) {
  textarea.addEventListener("input", function() {
    textarea.value = textarea.value.replace(/\n/g, "<br>").replace(/ /g, "<sp>");
  });
});
<textarea></textarea>

It could be done more simply, but I think this could be an interesting thing to learn from.

The first line gets all textareas on the page as a NodeList. Then, we loop through that NodeList with [].forEach.call, shortened from Array.prototype.forEach.call, because NodeLists don't have their own forEach.

The second line sets an event listener that triggers whenever the current textarea (in the loop) receives input. Event listeners wait for something to happen, and call functions whenever it does.

The third line sets the value of that textarea to whatever the current value is, with newlines (\n) replaced with <br> and spaces replaced with <sp>.

本文标签: javascriptHow to replace the line break in a textareaStack Overflow