Javascript:如何修剪可编辑的div内容

时间:2018-01-19 17:52:54

标签: javascript html contenteditable

我有一个可编辑的div,用户可以在其中编写文本以供评论。现在我想删除文本前后的空格。例如,当用户输入

"  Hello world   "

我必须插入

"Hello world" 

进入数据库。

我试过了

text.trim()

但它不起作用。我怎么能这样做?

另外如何删除重复的空行?

我想替换

<div>Hello</div>
<div></div>
<div></div>
<div></div>
<div>World</div>

通过

<div>Hello<div>
<div></div>
<div>World</div>

谢谢

5 个答案:

答案 0 :(得分:1)

您需要删除<br><div>非空字符串。请参阅以下内容:

function trimDiv(){



var text = document.getElementById("test").innerHTML.replace(/&nbsp;/gi, '').replace(/<div><br><\/div>/gi, '').replace(/<p><br><\/p>/gi, '');

//.replace(/<\/div>/gi, '');

document.getElementById("test").innerHTML=text;
}
<div id="test" contenteditable>   Hello World   </div>

<button id="trimText" onclick="trimDiv();">Trim</button>

编辑现在,代码剪切将保留一个重复的输入。 编辑2:也适用于IE 再试一次

答案 1 :(得分:0)

你有一个简单的方法来做到这一点...... 只需为您的标签或 div 使用宽度或高度您想要修剪它并在此相同的情况下使用一些样式....

<h6 style="height: 30px; overflow: hidden">some text you want to trim it....</h6>

之后不要显示你的文字 max-height > 30px ...

例如,如果你想修剪一个标签,你可以使用这样的 CSS:

width: 170px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

你会看到用 witdh 修剪:170px .... :)

我希望这个答案有帮助:)

答案 2 :(得分:-1)

它正在运行我在chrome控制台中尝试过它。要修剪javascript中的任何字符串,您可以使用trim()函数。要检查修剪是否有效,请使用string.length

修剪旧字符串的长度并修剪它
str = "  Hello World  "
alert(str.length)

trimmedString = str.trim()
alert(trimmedString.length)

答案 3 :(得分:-2)

使用正则表达式修剪文本

var _text ="      Hello world                  ";

//trimming space from left side of the string
function lTrim (data) {
	return data.replace(/^\s+/,"");
}
 
//trimming space from right side of the string
function rTrim(data) {
	return data.replace(/\s+$/,"");
}

_text = lTrim(_text);
_text = rTrim(_text);

console.log(_text);

答案 4 :(得分:-2)

这是:(工作示例)

<button style='width:auto; height:auto;'>my<br>button</button>
function filterTextarea(id){
var string = document.getElementById(id).value;
var result = string.replace(/(^[ \t]*\n)/gm, ""); // Remove lines
var result = result.trim(); // Remove spaces

console.log(result);
}

filterTextarea("example");