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?

iliketocode
  • 6,978
  • 5
  • 46
  • 60
Wayne Li
  • 375
  • 1
  • 4
  • 15

4 Answers4

5

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

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

21B5 is the unicode for

levi
  • 20,483
  • 7
  • 63
  • 71
  • 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,527
  • 1
  • 12
  • 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
  • 12,301
  • 14
  • 79
  • 125
Aleksandar Đokić
  • 1,940
  • 12
  • 30
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
  • 9,958
  • 17
  • 83
  • 129