2

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>
Kan Lam Tse
  • 41
  • 1
  • 3

3 Answers3

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 combine 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.com/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 combine 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.com/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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

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>.

Scott
  • 5,338
  • 5
  • 45
  • 70
  • *"Should replace as you type"* Making the text area effectively unusable, as it would reset your insertion point position constantly. – T.J. Crowder Mar 16 '15 at 15:58
  • Oh absolutely, but I don't think this is a pratical problem to begin with. – Scott Mar 16 '15 at 15:58