Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - replace all instances of a character in a string [duplicate]

People also ask

How can I replace all characters in a string using jQuery?

The replaceAll() method is an inbuilt method in jQuery which is used to replace selected elements with new HTML elements. Parameters: This method accepts two parameter as mentioned above and described below: content: It is the required parameter which is used to specify the content to insert.

Does string replace replacing all occurrences?

3.1 The difference between replaceAll() and replace()If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.

Does replace remove all occurrences?

replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)


'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers


RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
        })
    })
});

This does the replace once on each string, but it does it using a more specific selector.