How to change a string with jQuery?

3

I need to capture a string, grab a piece of it and swap this piece for another text.

<img src="/kit_150x150-12por-150x150.png">

I need to get the piece 150x150.png from src and switch to 238x238.png with jQuery . I can access the attribute more from there I can not get a piece and change the value of the text.

Can you help me?

    
asked by anonymous 23.04.2015 / 13:59

2 answers

5

Similar to @Ricardo only in function.

<script type="text/javascript" src="jquery-1.11.0.js"></script>
<img id="imgRotate" src="/kit_150x150-12por-238x238.png">

<script>
function changeImg(id, size){
    var src = jQuery('#'+id).attr('src');
    var src = src.replace(/\d+x\d+\.png/, size);
    jQuery('#'+id).attr('src', src);
}
changeImg('imgRotate', '266x266.png');
</script>
    
23.04.2015 / 14:28
4

If the values are static you can switch directly:

var src = "/kit_150x150-12por-150x150.png";
var src = src.replace("150x150.png", "238x238.png");

or dynamically using a regex (test it at link , it works with your example):

/[0-9]+[x|X][0-9]+.png/

Referencing a response from SOen , link to strings: Link

    
23.04.2015 / 14:12