【问题标题】:How to break to a new line when string contains "↵"? [duplicate]当字符串包含“↵”时如何换行? [复制]
【发布时间】:2016-12-08 13:12:44
【问题描述】:

我从 php 服务器得到一个像 var text = "aaaaaaa↵bbbbbb↵cccccc" 这样的字符串,我想把这个字符串输出到屏幕上。

当有“↵”时,以下文本换行。我正在使用 AngularJS。

我怎样才能通过使用纯 Javascript 或通过 AngularJS 来实现这一点?

【问题讨论】:

  • 或许将所有↵更改为<br/>
  • str = str.replace(\u21B5/g,'<br />');
  • @GeorgeStocker 您在\u21B5/g 的开头误写了/
  • style=" white-space: pre-wrap; " 可以使用css进行包装

标签: javascript angularjs


【解决方案1】:

尝试使用替换功能。它是纯 JavaScript。

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

21B5 的 unicode

【讨论】:

  • 这些解决方案都不适合我...就像 不存在,因此无法替换。我只能在浏览器控制台上看到它。
【解决方案2】:

您可以通过执行正则表达式轻松做到这一点:

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/>');

基本上,我们将数据存储在一个名为 text 的变量中,然后我们使用名为 replace 的字符串/正则表达式方法 .replace() 接受两个参数:搜索模式以及我们将要替换它的内容;

【讨论】:

  • 这仅替换第一次出现。
  • 是的,我的错,你必须添加代表全局的 g 参数,它将搜索任何出现然后替换它: text.replace(/↵/g, '
    ') ;
【解决方案3】:
var newString = mystring.replace(/↵/g, "<br/>");
alert(newString);

您可以找到更多here

【讨论】:

    【解决方案4】:

    使用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]); 
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2021-07-10
      • 2012-10-21
      • 2017-09-06
      • 2012-10-20
      • 2015-05-20
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多