首页 > javascript > 当数组字段为空时,替换值不起作用

当数组字段为空时,替换值不起作用 (Replacing values doesn't work ok when array field is empty)

2013-04-20 javascriptjquery

问题

我有这个代码:

$('#myTextArea').val($('#myTextArea').val().replace(linesText[4] + '\n', ""));

它工作正常。在这种情况下问题是:

$('#myTextArea').val() = "\n\n33333333333\n\n\n"

和linesText是这个数组:

0: ""
1: ""
2: "33333333333"
3: ""
4: ""
5: ""

我想要发生什么:$('#myTextArea')。val()成为“\ n \ n33333333333 \ n \ n”。

怎么了:

$('#myTextArea').val()

"\n33333333333\n\n".

发生这种情况是因为我实际上将“”+“\ n”替换为“”并且它取第一个“\ n”。我想拿第四个。如何解决这个问题?当linesText的字段不为空时,这种方法有效。

解决方法

我做了一个小功能,可能需要改进,但似乎工作:

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次出现)

如果函数在位置之前/之后找不到符号,则函数返回false,而如果一切正常,函数将返回没有第N位元素的字符串

问题

I have this code:

$('#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"

and linesText is this array:

0: ""
1: ""
2: "33333333333"
3: ""
4: ""
5: ""

What I want to happen: $('#myTextArea').val() to become "\n\n33333333333\n\n".

What happens:

$('#myTextArea').val()

becomes

"\n33333333333\n\n".

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

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)

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

相似信息