0

我有以下字符串:

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

谁能告诉我我在这里错过了什么?

谢谢,

4

5 回答 5

2

试试这个:

http://jsfiddle.net/aidioo7/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>
于 2013-03-27T04:33:27.330 回答
1

改变

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

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

Acarriage return将确保附加到前一行的行从下一行(它自己的)开始

于 2013-03-27T04:26:27.253 回答
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);
    }
于 2013-03-27T04:36:50.713 回答
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 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
于 2013-03-27T04:43:15.713 回答
0

尝试使用正则表达式

var stringLineToBeRemoved = 'cccccccc3';

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

演示:小提琴

于 2013-03-27T04:46:15.923 回答