根据Javascript中的换行符解析子串中的textarea

时间:2010-09-27 02:50:03

标签: javascript

我有一个需要解析的文本区域。需要拔出每个新线路并且需要对其执行操作。操作完成后,需要在下一行运行操作。这就是我现在所拥有的。我知道indexOf搜索不起作用,因为它逐个字符地搜索。

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);
}

因此,大部分时间都是用户输入。如果它有多个行,它将运行抛出每一行并单独运行submitinput。如果你们能帮助我,我会永远感恩。如果您有任何疑问,请询问

2 个答案:

答案 0 :(得分:22)

textarea的value内的换行符由换行符(大多数浏览器中为\r\n,IE和Opera中为\n)而非HTML <br>表示元素,因此您可以通过将换行符标准化为\n然后在textarea的值上调用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]";
});

答案 1 :(得分:1)

如果用户使用回车键转到文本区域的下一行,则可以写

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

textarea.value = textAreaString;