/    Sign up×
Community /Pin to ProfileBookmark

Replace function

Hi,
I need a statement to replace all old_char(s) with the new_char.
Looks like javascript replace() function only raplaces the first one.

st=’ABBACCADD’
st=st.replace(‘A’,’M’);

st=’MBBACCADD’ <– this is the current output.
st=’MBBMCCMDD’ <– This is what i want.

Please advice.

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@crh3675Jul 28.2004 — You need to set the "global" paramater:

st=st.replace(/A/g,'M');

or

var regexp="/A/g";

st=st.replace(eval(regexp),'M');
Copy linkTweet thisAlerts:
@CharlesJul 28.2004 — [i]Originally posted by crh3675 [/i]

[B]st=st.replace(eval(regexp),'M'); [/B][/QUOTE]
For reasons I don't want to go into, do not use that. If you want to define the pattern separately then use:

[font=monospace]<script type="text/javascript">

<!--

st = 'ABBACCADD'

pattern = new RegExp ('A', 'g')

st = st.replace(pattern,'M')

alert(st)

// -->

</script>[/font]

You should almost never use the "eval" function.
Copy linkTweet thisAlerts:
@crh3675Jul 29.2004 — Charles, thanks for the info. I was not aware you could pass the parameters as a second argument in a RegExp object. You learn something new everyday ?
Copy linkTweet thisAlerts:
@sciguyryanJul 29.2004 — Neither did i, Its nice to know though ?
Copy linkTweet thisAlerts:
@chadorbafauthorAug 02.2004 — Thanks Charles. Works perfect.
×

Success!

Help @chadorbaf spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...