7

I got a string like this var text = "aaaaaaa↵bbbbbb↵cccccc" from the php server, and I want to output this string to the screen.

When there is a "↵", the following text goes to a new line. I am using AngularJS.

How can I achieve this by using plain Javascript or through AngularJS?

John Smith
  • 7,243
  • 6
  • 49
  • 61
Wayne Li
  • 411
  • 1
  • 6
  • 16

4 Answers4

6

Try to use replace function. It's pure javascript.

text.replace(/\u21B5/g,'<br/>')

21B5 is the unicode for

levi
  • 22,001
  • 7
  • 73
  • 74
  • None of these solutions work for me... Its like the `↵` does not exist so it cant be replaced. I can only see it on the browser console. – Omar Oct 14 '19 at 20:34
3

You can easily do that by doing a regex:

var text = "aaaaaaa↵bbbbbb↵cccccc";

text.replace(/↵/, '<br/>');

this will only replace the first one, by adding the g (global) parameter we will replace any occurence of this symbol, we simply put the g after the / like so 
text.replace(/↵/g, '<br/>');

Basically here we store the data in a variable called text then we use the string/regex method called replace on it .replace() that takes two parameters: the pattern to search and with what we are going to replace it;

MaieonBrix
  • 1,584
  • 2
  • 14
  • 25
  • this remplaces only the first occurrence. – levi Aug 03 '16 at 02:00
  • Yeah my bad, you must add the g parameters which stands for global and that will search for any occurence and then replace it: text.replace(/↵/g, '
    ');
    – MaieonBrix Aug 03 '16 at 02:11
2
var newString = mystring.replace(/↵/g, "<br/>");
alert(newString);

You can find more here.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Aleksandar Đokić
  • 2,118
  • 17
  • 35
1

Use str.split([separator[, limit]]) : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

var text = "aaaaaaa↵bbbbbb↵cccccc";
for(var i=0;i<text.split('↵').length;i++){
    // use text[i] to print the text the way you want
    // separated by <br>, create a new div element, whatever you want
    console.log(text[i]); 
}
Doua Beri
  • 10,612
  • 18
  • 89
  • 138