Multiple Replace

hi!

i’m a newb at javascript and i’m trying to make a script, it works atm but i wonder if there an mutch easier way for my replace

First i’m using getElementsByTagName , this return something in the form of:

1x , 2x , 3x, …, 15x, etc…

I like to replace them to:

S01E, S02E, S03E …

at the moment i’m replacing everything apart like this:

good = bad.replace(/1x/, ‘S01E’).replace(/2x/, ‘S02E’).replace(/3x/, ‘S03E’) etc…

Can someone point me in the right direction to make this mutch cleaner ?

That modified technique that you’re using results in a leading 0 being added to ALL numbers.

If you do though want the leading 0 on all of them, there is a better replacement that can achieve that for you.


var good = bad.replace(/(\\d+)x/g, 'S0$1E');
// good is 'S01E , S02E , S03E, ..., S015E, etc...'

PMW,
Thank you.

Firstly, document.getElementsByTagName returns a collection of elements, so what do mean by 1x , 2x , 3x, …, 15x, etc… ? Do you mean the IDs of the elements or something else?

One way is to use a regular expression to convert 15x to S15E and likewise for all other numbers, and then to add a leading zero where required,


var bad = '1x , 2x , 3x, ..., 15x, etc...';
var good = bad.replace(/(\\d+)x/g, 'S$1E').replace(/S(\\d)E/g,'S0$1E');
// good is 'S01E , S02E , S03E, ..., S15E, etc...'

I tried this, it worked.


<script type="text/javascript">

var bad ="1x , 2x , 3x, ..., 15x, etc...";

var good = bad.replace(/(\\d+)(x)/g, "S0$1"+"$2".replace("$2","E") );

alert(good);

// good is 'S01E , S02E , S03E, ..., S015E, etc...'

</script>