• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 232
  • Last Modified:

Javascript replace...Need to replace all at once.

I have a string of numbers called "sTime".   The problem I'm having is that it's replacing my numbers in a sequential order, so if I have a 0 that gets replaced by a 6, when it goes down another 6 rows of code, it's replacing the 6 with a 2.   I only want it to replace it once, even though that number may appear more than once in the string.  For example,

00112 needs to be 66778 rather than 22334, which is wrong.   Help?   My code is below.

            sTime = sTime.replace(/0/g,'6');
            sTime = sTime.replace(/1/g,'7');
            sTime = sTime.replace(/2/g,'8');
            sTime = sTime.replace(/3/g,'9');
            sTime = sTime.replace(/4/g,'0');
            sTime = sTime.replace(/5/g,'1');
            sTime = sTime.replace(/6/g,'2');
            sTime = sTime.replace(/7/g,'3');
            sTime = sTime.replace(/8/g,'4');
            sTime = sTime.replace(/9/g,'5');
  • 2
1 Solution
Use : sTime.replace(/\d/g, function($1) { return [6,7,8,9,0,1,2,3,4,5][$1]; })

sTime = "00112";
alert(  sTime.replace(/\d/g, function($1) { return [6,7,8,9,0,1,2,3,4,5][$1]; })  );


Open in new window

work too :
sTime = sTime.replace(/\d/g, function($1) { return (-$1-6) * -1; });

Open in new window

or again :
sTime = sTime.replace(/\d/g, function($1) { return Math.abs(-$1-6); });

Open in new window

saturationAuthor Commented:
Great...Now I have another similar question related to this.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now