Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace doesn't work [duplicate]

function areaMe(area) {
    var barea = $('#barea').val();
    if (barea.indexOf(area) != -1) {
        alert ("..." + barea + "..." + area + "...");
        barea.replace(area, "cu"); // Remove
        alert ("..." + barea + "..." + area + "...");
    }
    else {
        barea += area + ' '; // Include.
    }
    $('#barea').val(barea);
}
like image 468
Paulo Bueno Avatar asked Dec 11 '09 21:12

Paulo Bueno


People also ask

Why replace is not working in JavaScript?

The "replace is not a function" error occurs when we call the replace() method on a value that is not of type string . To solve the error, convert the value to a string using the toString() method before calling the replace() method.

How to use the replace function in JavaScript?

To perform a global search and replace, use a regular expression with the g flag, or use replaceAll() instead. If pattern is an object with a Symbol. replace method (including RegExp objects), that method is called with the target string and replacement as arguments.

Does replace replace all occurrences?

The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.

How to replace using RegEx in JavaScript?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.


2 Answers

barea = barea.replace(area, "cu")

You need to assign it since String.prototype.replace isn't a mutator method.

like image 88
meder omuraliev Avatar answered Oct 23 '22 04:10

meder omuraliev


You need to assign the replaced value back to your variable:

barea = barea.replace(area, "cu");
like image 45
Gumbo Avatar answered Oct 23 '22 05:10

Gumbo