jQuery从字符串块中删除行的问题

时间:2013-03-27 04:15:45

标签: javascript jquery

我有以下字符串:

aaaaaaaa1
bbbbbbbb2
cccccccc3
dddddddd4

这是我的领域:

<textarea id="myLinesField"></textarea>

使用jQuery,说过我可以选择并删除任何行(按任意顺序),我试图从我的行中删除特定行,说第二行得到如下所示的确切结果:

aaaaaaaa1
cccccccc3
dddddddd4

这是我的代码:

var value = $('#myLinesField').val();
var newVal = recipientValue.replace(stringLineToBeRemoved,'');
var finalResults = newVal.replace("\n", "");
$('#myLinesField').val(finalResults);

但在某些情况下我会得到类似的东西(并非总是如此):

aaaaaaaa1cccccccc3

dddddddd4

谁能告诉我在这里缺少什么?

谢谢,

5 个答案:

答案 0 :(得分:2)

试试这个:

<强> http://jsfiddle.net/adiioo7/SpnrN/

JS:

jQuery(function ($) {
    $("#btnSubmit").on("click", function () {
        var value = $('#myLinesField').val();
        var newVal = value.replace($("#strToRemove").val(), '');
        var finalResults = newVal.replace("\n", "");
        $('#myLinesField').val(finalResults);
    });
});

HTML:

<textarea id="myLinesField" style="height:100px;width:100px;">aaaaaaaa1 bbbbbbbb2 cccccccc3 dddddddd4</textarea>
<br/>
<br/>Please enter the string to remove :
<input type="text" id="strToRemove"></input>
<input type="button" id="btnSubmit" value="submit"></input>

答案 1 :(得分:1)

更改

var finalResults = newVal.replace("\n", "");

var finalResults = newVal.replace("\n", "\r");

carriage return将确保自己附加到上一行的行在下一行(自己的行)上开始

答案 2 :(得分:0)

试试这个:

    var stringLineToBeRemoved = "bbbbbbbb2";
    var foundin = $('textarea:contains("'+stringLineToBeRemoved+'")');
    if(foundin)
    {
        var value = $('#myLinesField').val();
        var newVal = value.replace(stringLineToBeRemoved,'');
        var finalResults = newVal.replace("\n", "");
        $('#myLinesField').val(finalResults);
    }

答案 3 :(得分:0)

您可以尝试这种方法(请参阅工具示例的小提琴:http://jsfiddle.net/amyamy86/29evM/):

var removeStr = function (str, index) {
    var parts = str.replace(/$(\s)*/gm, "\n").split("\n");
    parts.splice(index, 1);
    return parts.join("\n");
};

如果您的textarea是:

<textarea id="myLinesField">aaaaaaaa1
bbbbbbbb2

cccccccc3
dddddddd4</textarea>

然后:

var recipientValue = $('#myLinesField').val();
var finalResults = removeStr(recipientValue, 1);  // removes the 2nd line (non-empty line)

将屈服:

aaaaaaaa1
cccccccc3
dddddddd4

答案 4 :(得分:0)

尝试使用regexp

var stringLineToBeRemoved = 'cccccccc3';

var value = $('#myLinesField').val();
var regex =  new RegExp(stringLineToBeRemoved + '(\r\n|\n|\r)', 'm');
$('#myLinesField').val(value.replace(regex,''));

演示:Fiddle