简体   繁体   English

如何用换行符代替分号?

[英]How to replace semicolon with newline?

I want to replace semicolon with new line. 我想用新行替换分号。
ie whenever semicolon applears it has to move to new line. 即,每当分号applears时,都必须移至新行。
I tried .replace() . 我尝试了.replace() It was not working for new line but was working for some other string. 它不适用于换行,但适用于其他字符串。 One more problem is only the first semicolon will be replaced. 另一个问题是只有第一个分号将被替换。

Here is my code snippet: 这是我的代码段:

<p>{{X.content.replace(';', '\n')}} </pre>

This was not working, then i tried with: 这不起作用,然后我尝试了:

<p> {{X.content.replace(';', 'REPLACE')}} </p>

The code was working with any other string but only the first semicolon (;) will be replaced. 该代码可与任何其他字符串一起使用,但仅第一个分号(;)将被替换。

I want this to be converted and appear in the new line 我希望将其转换并显示在新行中

first line; 第一行; second line; 第二行; third line; 第三行

You need a regex with global flag to change all instances 您需要一个带有全局标志的正则表达式来更改所有实例

X.content.replace(/;/g, '\n')

this is not something you should be doing in the view. 这不是您应该在视图中执行的操作。 Suggest you create a filter or modify the data in controller 建议您创建过滤器或修改控制器中的数据

try like this here is one working example 像这样尝试,这是一个工作示例

var x ="dsdfs;sfsf;fdsfs"
console.log(x)//"dsdfs;sfsf;fdsfs"

var y  =x.replace(/;/g, " \n ")
 console.log(y)
 //"dsdfs 
   sfsf 
   fdsfs"

There are a few different things going wrong for you: 您可能会遇到一些不同的问题:

Only thie first semicolon is replaced: 仅替换第一个分号:

This is the default for JavScript. 这是JavScript的默认设置。 A regex will replace the rest. 正则表达式将替换其余部分。

X.content.replace(/;/g, '\n')

The newlines don't show up: 换行符不会显示:

This is because HTML does not respect newlines by default. 这是因为HTML默认情况下不遵守换行符。 You seam to have realised this because you have writen <p></pre> (which is odd and broken). 您可能已经意识到了这一点,因为您已经写了<p></pre> (这很奇怪而且很残破)。

Either: 或者:
Replace ; 更换; with \\n and then use a well formed pre: 使用\\n ,然后使用格式正确的pre:

<pre>{{X.content.replace(/;/g, '\n')}}</pre>

Or: 要么:
Replace ; 更换; with <br /> and then declare the result as html: 使用<br /> ,然后将结果声明为html:
(Warning: this option leaves you open to injection attacks so you need to make sure you trust the content) (警告:此选项使您容易受到注入攻击,因此需要确保您信任内容)

<p ng-bind-html="X.content.replace(/;/g, '<br />')"></p>


EDIT: 编辑:

Probably a better approach for you would be to forget all that and just do: 对您来说,更好的方法可能是忘记所有这些,然后执行:

<p ng-repeat="line in X.content.split(';')">{{line}}</p>

This is less risky and results in nicer HTML to style as you choose. 这样可以降低风险,并且可以使您选择的HTML样式更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM