0

I am a sucker at Regular Expressions, I have learnt a few things about them but I can't get my head around them. There's part of a string that i need to extract from some HTML code but I don't know how to use regular expressions to do it.

I know that str.match() function takes in either a regular expression or a string and returns it. I would like to use this function to extract part of the string.

This is my code:

<img src="images/1.jpg" class="imgs" />
<img src="images/2.jpg" class="imgs" />
<img src="images/3.jpg" class="imgs" />

<script>
    var str = document.getElementsByClassName('imgs');  // str that is being matched
    var re = /^"images/.*"$/;
    var res = str[0].match(re);    // returns undefined is not a function
</script>

The 'images/1.jpg' is from an array that is sequential with the numbers. ie . 'images/1.jpg', 'images/2.jpg'.

I want to extract the "images/(num).jpg", whichever number it may be, i need to extract the "images" with the number. The final result should be "images/(num).jpg".

Is it possible to do it with str.match and regular expressions or some other technique should be used?

1 Answer 1

1

if the image will always be a jpg you can do:

<img src="images/1.jpg" class="imgs" />
<img src="images/2.jpg" class="imgs" />
<img src="images/3.jpg" class="imgs" />

<script>
    var str = document.getElementsByClassName('imgs');  // str that is being matched
    var re = /images\/[0-9]+\.jpg/g
    var res = str[0].src.match(re)[0];    
</script>

this will return the string you're looking for.

Sign up to request clarification or add additional context in comments.

7 Comments

please explain the answer..I don't get why you did str.match(re)[0].
Since number's are always a part of the file. You may replace * with a +.
match will give you an array of matches, if there's one match, than [0] will give you it as a string.. with out the [0] you'll get an array with one value
it does work..+1 for working..but me code still didn't work how i needed it to
sure, the reason it's not working is a few errors in your code.. I've edited your above question with comments where I see problems, basically your variable 'str' is returning an array of elements so you can't treat it as string.. you need to grab the src 'str[0].src' as I've written over your example above
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.