ibaris
ibaris

Reputation: 156

Create a Regular expression using the gi flags from a variable

var metin = "baris";
var icerikoku = "Hello Baris. What is surname Baris. Bye bye baris. How are you metin.";
var n = icerikoku.replace(/metin/gi, "ziya");
$("#icerikoku").html(n);

print:
Hello Baris. What is surname Baris. Bye bye baris. How are you ziya.

but, must be:
Hello ziya. What is surname ziya. Bye bye ziya. How are you metin.

Upvotes: 0

Views: 190

Answers (1)

antyrat
antyrat

Reputation: 27765

You need to use RegExp constructor for that:

var n = icerikoku.replace(new RegExp(metin, 'gi'), "ziya");

This will allow you to pass variables to your regexp.

Upvotes: 7

Related Questions