Reputation: 243
I am writing a function which is used to replace the class of div in certain conditions, for example,
these 4 numbers might be the same, like 1_1_1_1, my demo coding is like var str = 'e_new_hazard_frame_2_1'; str = str.replace(/_[_0-9]*)$/,'1');
it seems not correct can anyone teach me how to do it? thank you so much!
Upvotes: 0
Views: 103
Reputation: 2522
Try this one.It may help you.
<div class="e_new_hazard_frame_2_1_4_7">click to change value</div>
<script type="text/javascript">
$(".e_new_hazard_frame_2_1_4_7").on('click',function(){
change_class(7); //change the value from here i.e 2,4,1,7
});
function change_class(p)
{
var number_change=p;
switch (number_change)
{
case 2:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[2]/g,'1');
break;
case 1:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[1]/g,'4');
break;
case 4:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[4]/g,'6');
break;
case 7:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[7]/g,'3');
break;
}
$(".e_new_hazard_frame_2_1_4_7").html(str);
}
</script>
Please let me know if you face any problem.
Upvotes: 1
Reputation: 4988
Maybe use a function to handle the numbers however you want?
function replacer(match, p1, p2, p3, p4, offset, string){
// p1-4 are your numbers
// (they are strings right now, sto make +p1 to convert them to int)
p1= +p1 + 1;
p2= +p2 + 1;
p3= +p3 + 1;
p4= +p4 + 1;
// fixed a small bug here
return ['', p1, p2, p3, p4].join('_');
};
var str = "asdasdasd_1_2_3_4";
str = str.replace(/_(\d)_(\d)_(\d)_(\d)/, replacer);
Upvotes: 0
Reputation: 154
I think it might be useful to you `str='e_new_hazard_frame_2_1';
if(conditin1)
{
pattern = /[2]/g;
str = str.replace(pattern,'1');
}
if(conditin2)
{
pattern = /[1]/g;
str = str.replace(pattern,'4');
}
if(conditin3)
{
pattern = /[4]/g;
str = str.replace(pattern,'6');
}
if(conditin4)
{
pattern = /[7]/g;
str = str.replace(pattern,'3');
}`
Upvotes: 0
Reputation: 2368
In PHP
echo str_replace("2","1","e_new_hazard_frame_2_1_4_7");
For more reference visit this. Hope this will help you.
In JavaScript
str.replace("e_new_hazard_frame_2_1_2_4","e_new_hazard_frame_1_1_2_4");
For more reference visit this
Upvotes: 0
Reputation: 1010
This will replace all occurrence of 2 to 1 in str:
var str = 'e_new_hazard_frame_2_1_2_4';
str = str.replace(/2/g,'1');
To replace the class of your div:
var target_class = 'e_new_hazard_frame_2_1_4_7';
$('.'+target_class).removeClass(target_class).addClass(target_class.replace(/2/g,'1'))
Upvotes: 0