Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove certain text from textarea in Javascript

I need a little input on the best way to remove a certain word or phrase in a text area. I have an input field entitled input. I want to search that area for the word that is put into a form field called name and then removed from input. None of the code I have tried works, and most search results yield irrelephant.

function delete() {
    var name = document.getElementById("name").value;
    var textarea = document.getElementById("input").value;
    var data = textarea.length;
    for (var i = 0; i < data.length; i++) {
        if (textarea.substr(i, data) == name) {
            textarea.value = "";
        }
    }
}

What I tried earlier with no luck.

like image 208
Seth Earby Avatar asked May 03 '26 11:05

Seth Earby


2 Answers

Not sure what you are trying to do, but this is the correct code: (there are many mistakes in your code)

function deleteValue() {  //instead of "delete"
    var name = document.getElementById("name");
    var textarea = document.getElementById("result");  //intead of "input"
    var data = textarea.value;
    for (var i = 0; i < data.length; i++) {
        if (data.substr(i, data) == name.value) {
            textarea.value = "";
        }
    }
}

Some points to consider:

  • Change your text input name from input to something else because it is a tag name.
  • You can't have a function name delete because it is a reserved word in javascript. use something else like deleteValue.

UPDATE:

I think this is what you are looking for..

function deleteValue() {
    var name = document.getElementById("name");
    var textarea = document.getElementById("result");
    textarea.value = textarea.value.replace(name.value, "");
}

Working Fiddle

like image 62
Mr_Green Avatar answered May 06 '26 00:05

Mr_Green


You can add replaceAll function to String object. If you want to remove all occurrences of specific text.

(function() {   
    if (!String.replaceAll) {
        String.prototype.replaceAll = function replaceAll(replace, value) {
            return this.replace(new RegExp(replace, 'g'), value);
        };
}
}());

And modify delete function should look like this:

function deleteValue() {
    var name = document.getElementById('name');
    var textarea = document.getElementById('result');
    var data = textarea.value;
    textarea.value = textarea.value.replaceAll(name.value, "");
} 
like image 20
maketest Avatar answered May 06 '26 00:05

maketest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!