global string replace w/o regex?

K

kilik3000

How do you do a global replace in a string without using a regex?

For example,

"ABBA".replace("B", "") returns -> "ABA" // I'd like this to be a
global replace
"ABBA".replace(/B/g, "") returns -> "AA" // this works correctly but
requires a regex

The reason I ask is that I'd like to have a function that just takes a
single character as an argument and then passes that character to
replace. So the "B" in my example would be a param/variable.

If I have to use a regex is there a way to parameterize it?

var b = "B";
"ABBA".replace(/b/g, "")

Does not work.

-Thx
 
M

Martin Honnen

The reason I ask is that I'd like to have a function that just takes a
single character as an argument and then passes that character to
replace. So the "B" in my example would be a param/variable.

If I have to use a regex is there a way to parameterize it?

var b = "B";
"ABBA".replace(/b/g, "")

Use the RegExp constructor:

var b = "B";
"ABBA".replace(new RegExp(b, "g"), "")
 
S

scripts.contact

How do you do a global replace in a string without using a regex?

function replace(str,rep,rWith){
return str.replace(new RegExp(rep.replace(/([\^\$\\\.\+\*\?\{\}\(\)\|
\[\]])/g,'\\$1'),"g"),rWith)
}
alert(replace("sdsd.dasd",".","-"))
 
D

dd

Use the RegExp constructor:

var b = "B";
"ABBA".replace(new RegExp(b, "g"), "")
Martin Honnen

The OP could also make a new String prototype method
which I've called rep here:

String.prototype.rep=function(b){
return this.replace(new RegExp(b,"g"),"");
}

and why not this one too (replace with):

String.prototype.repw=function(b,w){
return this.replace(new RegExp(b,"g"),w);
}
 
L

-Lost

dd said:
The OP could also make a new String prototype method
which I've called rep here:

String.prototype.rep=function(b){
return this.replace(new RegExp(b,"g"),"");
}

and why not this one too (replace with):

String.prototype.repw=function(b,w){
return this.replace(new RegExp(b,"g"),w);
}

Or better still:

String.prototype.repw=function(b,w){
var w = w || '';
return this.replace(new RegExp(b,"g"),w);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top