Skip to content Skip to sidebar Skip to footer

Replacing Values Doesn't Work Ok When Array Field Is Empty

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\n3333

Solution 1:

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

Solution 2:

I believe this could be what you want to do

var parts = $('#myTextArea').val().split('\n');
parts[4].replace(linesText[4] + '\n', "");
$('#myTextArea').val(parts.join(''));

Post a Comment for "Replacing Values Doesn't Work Ok When Array Field Is Empty"