用单个空格和多个“”元素替换连续空间

时间:2011-09-22 14:20:28

标签: html c#-2.0 space

我有一个html文档,其中包含某些节点中的空格。例如,

<B>This is          Whitespace      Node </B>

当在浏览器中显示此html时,html中的多个连续空格始终显示为一个空格。为了避免这个问题,我想用一个空格和多个&nbsp;元素替换连续空格。

实现这一目标的最佳解决方案是什么?

我正在使用C#2005。

4 个答案:

答案 0 :(得分:2)

试试这个,

string str = "<B>This is          Whitespace      Node </B>";
Regex rgx = new Regex("([\\S][ ])");
string result = rgx.Replace(str, "$1.")
                        .Replace(" .","?")
                        .Replace(" ","&nbsp")
                        .Replace("?"," ");

答案 1 :(得分:1)

根据http://www.w3.org/TR/CSS2/text.html#white-space-prop

使用CSS的white-space属性
white-space: pre-wrap

或者,如果你真的想用bruteforce来做,用一个非破坏空间和一个普通空间替换两个连续的空格......我强烈建议不要这样做。

string text = originalText.Replace("  ", "&nbsp; ");

答案 2 :(得分:0)

你可以尝试

String.Replace("  ", " ")

如果你喜欢正则表达式

Regex rgx = new Regex("([ \t]|&nsbp)+");
string result = rgx.Replace(input, " ");

答案 3 :(得分:0)

我假设你是从代码背后设置控件的值?如果是那么......

<strong><asp:Literal id="myLiteral">This is          Whitespace      Node </asp:Literal></strong>

在代码背后......

var myText = "This is          Whitespace      Node ";
myLiteral.Text = myText.Replace(" ", "&nbsp;");

如果文字中没有代码或没有代码......

<strong><%= "This is          Whitespace      Node ".Replace(" ", "&nbsp;") %></strong>
相关问题