我从 API 获取数据,它返回 XML,我已经将其转换为 json,因为我使用 angularjs,我需要的字段,存储歌曲歌词,它使用了这个符号 ↵
什么时候它应该转到新行。
例如:
You shout it loud↵But I can’t hear a word you say↵I’m talking loud, not saying much↵↵I’m criticized but all your bullets ricochet↵You shoot me down, but I get up
上面的例子是我使用 console.log()
时得到的结果但是当我将此字段显示到我的 HTML 页面时,它只是没有 ↵
的字符串在里面。我不知道为什么它不显示在 HTML 中,如果需要换行,它也不会发生。
我正在考虑替换 ↵
与 <br />
是否可以?如果你们能帮助我,我将不胜感激。
更新: 我使用 angularjs 并用歌词填充模型,并在我的 html 中用 {{lyric}} 显示它
但是正如你在图片中看到的,当我使用 console.log($scope.lyric) 时,字符串的格式很好,但是当我在 HTML 中显示相同的模型时,它是这样的
最佳答案
简单的正则表达式字符串替换应该可以解决它:
var str = 'You shout it loud↵But I can’t hear a word you say↵I’m talking loud, not saying much↵↵I’m criticized but all your bullets ricochet↵You shoot me down, but I get up';
var formatted = str.replace(/↵/ig, "<br/>\n");
console.log(formatted);
document.write(formatted);
正则表达式找到与 /
之间的字符匹配的所有内容。签署并用标准换行符 \n
替换它们和 HTML 断线标记 <br/>
.
i
和g
标志的意思是 Case Insensitive
和Search Global
分别。
Case Insensitive
捕获字符,即使它们的大小写不同。 Search Global
意味着如果您输入多行字符串,那么它将替换所有行,而不仅仅是第一行。
关于javascript - 如何从 xml 响应字符串创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40102504/