2010-09-27 49 views
11

我有一個需要解析的文本區域。每條新生產線都需要拔出,並且需要對其進行操作。操作完成後,需要在下一行運行該操作。這是我目前所擁有的。我知道indexOf搜索將無法正常工作,因爲它正在逐字搜索。根據Javascript中的換行符來解析子字符串中的textarea

function convertLines() 
{ 
trueinput = document.getElementById(8).value; //get users input 
length = trueinput.length; //getting the length of the user input 
newinput=trueinput; //I know this looks silly but I'm using all of this later 
userinput=newinput; 
multiplelines=false; //this is a check to see if I should use the if statement later 
    for (var i = 0; i < length; i++) //loop threw each char in user input 
     { 
      teste=newinput.charAt(i); //gets the char at position i 
      if (teste.indexOf("<br />") != -1) //checks if the char is the same 
       { 
//line break is found parse it out and run operation on it 
        userinput = newinput.substring(0,i+1); 
        submitinput(userinput); 
        newinput=newinput.substring(i+1); 
        multiplelines=true; 
       } 
     } 
    if (multiplelines==false) 
     submitinput(userinput); 
} 

因此,大多數情況下它採用userinput。如果它有多條線,它將運行投擲每條線並分別運行submitinput。如果你們能幫助我,我會永遠感激。如果您有任何疑問,請向

回答

1

如果用戶使用的輸入鍵轉到您的textarea的下一行,你可以寫,一個textarea的value

var textAreaString = textarea.value; 
textAreaString = textAreaString.replace(/\n\r/g,"<br />"); 
textAreaString = textAreaString.replace(/\n/g,"<br />"); 

textarea.value = textAreaString; 
21

換行符用線表示(IE和Opera中的\r\n,在IE和Opera中爲\n),而不是HTML <br>元素,因此可以通過將換行符歸一化爲\n,然後調用文本區域值的split()方法來獲取各個行。這裏是一個實用函數,它爲每一行textarea值調用一個函數:

function actOnEachLine(textarea, func) { 
    var lines = textarea.value.replace(/\r\n/g, "\n").split("\n"); 
    var newLines, i; 

    // Use the map() method of Array where available 
    if (typeof lines.map != "undefined") { 
     newLines = lines.map(func); 
    } else { 
     newLines = []; 
     i = lines.length; 
     while (i--) { 
      newLines[i] = func(lines[i]); 
     } 
    } 
    textarea.value = newLines.join("\r\n"); 
} 

var textarea = document.getElementById("your_textarea"); 
actOnEachLine(textarea, function(line) { 
    return "[START]" + line + "[END]"; 
});