Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace with variable?

Tags:

jquery

replace

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?

like image 501
Shpigford Avatar asked Jan 23 '12 16:01

Shpigford


People also ask

What is the use of replacewith () method in jQuery?

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.

How to replace strings in HTML with jQuery?

$("#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.

How to replace text globally using jQuery replace method?

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:

How to replace all occurrences of a string in jQuery?

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


2 Answers

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

like image 98
Jamiec Avatar answered Oct 17 '22 14:10

Jamiec


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"));
like image 31
ShankarSangoli Avatar answered Oct 17 '22 12:10

ShankarSangoli