I'm trying to do a replace
on a string like this:
$('#example_id').replace(/abc123/g,'something else')
But the abc123
actually needs to be a variable.
So something like:
var old_string = 'abc123'
$('#example_id').replace(/old_string/g,'something else')
So how would I use a variable in the replace function?
Explanation: replaceWith () method provided by jQuery replaces each element in the set of matched elements with the new content. In the given example, on button click, the content of “pid” element gets replaced with the string “jQuery replaceWith” as shown below.
$("#element").text("What's up!"); In a similar way, we can replace the whole HTML content by using the html function: By using jQuery in combination of JavaScript functions we are able to replace strings in elements, texts and even JavaScript variables.
1. Replacing a text globally using jQuery replace method: string.replace (/ [old string]/+/g, ‘new string’) 2. Replacing a target element using replaceAll () method: $ (content).replaceAll (selector) 3. Replacing the selected content with the new one using replaceWith () method:
Using the replace () method of jQuery, we can find and replace all the occurrences of a particular substring in a string or a string in a group of strings. jQuery also offers two other methods for DOM manipulation with replace feature, replaceAll (), and replaceWith (). replaceAll () method is used to replace each target element with a set ...
There is another version of replace which takes a RegExp
object. This object can be built up from a string literal:
var old_string = "abc123";
var myregexp = new RegExp(old_string,'g');
$('#example_id').replace(myregexp,'something else')
Some useful info here
First of $('#example_id')
will give you a jQuery object, you must be replacing string inside its html or value. Try this.
var re = new RegExp("abc123","g");
$('#example_id').html($('#example_id').html().replace(re, "something else"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With