-1

I want to replace multiple occurrences of 'text1' with 'text2', in '#area', here is my code that works just fine:

var replaced = $('#area').html().replace(/text1/g, 'text2');
$('#area').html(replaced);

But imagine the 'text1' is a value of an input box, so:

var search = $('#blah').val();
var replaced = $('#area').html().replace(/search/g, 'text2'); <--- HERE IS THE PROBLEM
$('#area').html(replaced);

As you can see in the second line, I did /search/g but it's not working, how should I put the search value there?

user2864740
  • 60,010
  • 15
  • 145
  • 220
behz4d
  • 1,819
  • 5
  • 35
  • 59

3 Answers3

1

If search is a variable, you need to use a dynamic regex(RegExp)

if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return value.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")
    };
}

//then later in your method
var search = $('#blah').val();
var regex = new RegExp(RegExp.escape(search), 'gi');
var replaced = $('#area').html().replace(regex, 'text2');
$('#area').html(replaced);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Or even simpler:

var search = $('#blah').val();
var re = new RegExp(search, 'g');

str = str.replace(re, '');
Nicholas Rubin
  • 317
  • 1
  • 4
  • 14
0

HTML:

Replace String:
<input type="text" id="blah" />
<br/>Text:
<input type="text" id="area" />
<br/>
<button onclick="myReplace()">Replace</button>

JS:

function myReplace() {
    var search = $('#blah').val();
    var regex = new RegExp(search, 'g');
    var replaced = $('#area').val().replace(regex, 'text2'); 
    $('#area').val(replaced);
}

JSFIDDLE

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99