How to swap a string with jQuery?

Asked

Viewed 328 times

3

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

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

I need to get the piece 150x150.png of src and trade for 238x238.png with jQuery. I can access the attribute more from there I can’t take a piece and change the value of the text.

Can you help me?

  • It does not change no, so I put the . png next in the question !!!

2 answers

5

Similar to @Ricardo’s only 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>

4

If the values are static you can exchange directly:

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

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

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

Referencing a response from Soen that can help you connect the strings: Link

Browser other questions tagged

You are not signed in. Login or sign up in order to post.