我有以下字符串:
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
谁能告诉我在这里缺少什么?
谢谢,
答案 0 :(得分:2)
<强> http://jsfiddle.net/adiioo7/SpnrN/ 强>
jQuery(function ($) {
$("#btnSubmit").on("click", function () {
var value = $('#myLinesField').val();
var newVal = value.replace($("#strToRemove").val(), '');
var finalResults = newVal.replace("\n", "");
$('#myLinesField').val(finalResults);
});
});
<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