如何使用javascript中的字符串函数从字段值中获取前n个字符

时间:2014-04-17 15:27:54

标签: javascript

我正在尝试修剪html字段的值,但我不能 这是我的代码

var string=document.getElementById("id").value;
var length = 6;
var trimmedString = string.substring(0, length);
document.getElementById("id2").innerHTML=trimmedString;

html代码:

  

<textarea id="id"></textarea> <div id="id2"></div>

但div(id2)中的数据不会改变 帮助!!

1 个答案:

答案 0 :(得分:1)

试试这个:

function trim( str ) { // removes whitespaces from the beginning and from the end of the specified string, returns trimmed string
    return str.replace(/^\s+|\s+$/g,"");
}

var arr = ["  one ", " two", "three "];

arr.forEach(function(value) {
    console.log(trim(value));
});

JSFIDDLE