javascript 在字符串 jquery 中添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11308689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:42:41  来源:igfitidea点击:

Adding space in a string jquery

javascriptjquery

提问by kiran kumar

I wanto to insert a space at the start of my string Example:

我想在字符串的开头插入一个空格示例:

MySite
   MySite (I want this)

I have tried in this mode but nothing

我试过这种模式,但没有

txt="    "+v.text();

Can someone help me? Thanks a lot

有人能帮我吗?非常感谢

回答by sushil

Try :

尝试 :

 txt="    "+v.text();

The other good solution would be to use div with some style set on it.

另一个好的解决方案是使用带有一些样式设置的 div。

 <div style='margin-left:15px' id='main_text'></div>

You could use jQuery to place txt in the div.

您可以使用 jQuery 将 txt 放在 div 中。

     txt= v.text();
     $('#main_text').html(txt);

回答by Fabrizio Calderan

A solution is to fill the spaces with &nbsp;entities, but if you have to achieve this effect just for styling/visualization purpose, then wrap that line in a proper tag and use some CSS instead (e.g. text-indentproperty)

一种解决方案是用&nbsp;实体填充空间,但如果您必须仅出于样式/可视化目的而实现此效果,则将该行包装在适当的标签中并使用一些 CSS(例如text-indent属性)

if you have to indent text inside a select (as I guess reading your previous answer) you may want to wrap your options inside an optgroupelement (and give it some padding)

如果您必须在选择中缩进文本(正如我想阅读您之前的答案),您可能希望将您的选项包装在一个optgroup元素中(并给它一些填充)

回答by kiran kumar

var str2 = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Here goes your string with spaces";

回答by Durgaprasad Budhwani

There are 2 solutions below :-

下面有两种解决方案:-

1. txt="<pre>    </pre>"+v.text();


2. txt="<span style='margin-left:15px'></span>"+v.text();