0

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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.