从字符串中删除空格并以分隔的行写入文本

时间:2014-11-08 07:17:09

标签: javascript html

我想删除不必要的空间,并在textarea的分隔行中写入内容。
实施例

ABC
ABCDE
ABD

将其转换为:

ABC
ABCDE
ABD

1 个答案:

答案 0 :(得分:1)

你需要做两件事:

  1. 从TextArea
  2. 中抓取内容
  3. 遍历线条并修剪每条线条(删除所有空行)
  4. CODE:

    var content = myTextArea.value;
    
    //Split into lines
    var lines = content.split( /\r?\n/ );
    
    //Your new content
    var newContent = "";
    
    //Loop through all lines
    for ( var i = 0; i < lines.length; i++ )
    {
        //Trim it first
        var line = lines[ i ].trim();
    
        //Empty line, remove it
        if ( line === "" ) continue;
    
        //Add to new content
        newContent += line + "\n";
    }
    
    //Save to text area
    myTextArea.value = newContent;