数组字段为空时,替换值无法正常工作 [英] Replacing values doesn't work ok when array field is empty
问题描述
我有此代码:
$('#myTextArea').val($('#myTextArea').val().replace(linesText[4] + '\n', ""));
,它工作正常.问题是在这种情况下:
and it works fine. The problem is in this case:
$('#myTextArea').val() = "\n\n33333333333\n\n\n"
和linesText是此数组:
and linesText is this array:
0: ""
1: ""
2: "33333333333"
3: ""
4: ""
5: ""
我想发生的事情:$('#myTextArea').val()变成"\ n \ n33333333333 \ n \ n".
What I want to happen: $('#myTextArea').val() to become "\n\n33333333333\n\n".
会发生什么:
$('#myTextArea').val()
成为
"\n33333333333\n\n".
之所以会发生这种情况,是因为我实际上用"替换了" +"\ n",并且使用了第一个"\ n".我想拿第四. 如何解决这个问题? 当linesText的字段不为空时,此方法有效.
This happens because I actually replace "" + "\n" with "" and it takes the first "\n". I want to take the fourth. How to fix this? This works when linesText's fields aren't empty.
推荐答案
我做了一个可能需要改进的小功能,但是似乎可以用:
i've made a small function that probably needs improvement, but seems to work:
var ok = "\n\n33333333333\n\n\n";
function replaceSymbol(dataStr, toFind, elemPos) {
var spacing = toFind.length;
var indexToReplace = 0 - spacing;
var curString;
for (var i = 0; i < elemPos; i++) {
curString = dataStr.substr(indexToReplace + spacing);
if (curString.indexOf(toFind) == -1)
return false;
indexToReplace = indexToReplace + curString.indexOf(toFind) + spacing;
}
return dataStr.substr(0, indexToReplace) + dataStr.substr(indexToReplace + spacing);
}
replaceSymbol(ok, '\n', 4);
此函数要求输入3个参数,即字符串(ok),要替换的符号('\ n')和位置(在本例中为该符号的第4次出现)
this function ask for 3 parameters, the string (ok), the symbol to replace ('\n') and the position (in this case the 4th occurence of the symbol)
如果该函数在该位置之前/之后找不到符号,则该函数返回false,而如果一切正常,该函数将返回不包含元素在第N个位置的字符串
if the function can't find the symbol before/in the position, the function return false, while if all is ok the function will return the string without the element in Nth position
这篇关于数组字段为空时,替换值无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!