you can use ?
at end of group for optional group patterns:
its work fine: /(<imgs)[^>]*(src=S+)[^>]*(salt=["|'].*?["|'])?[^>]*(/?>)/gm
and here the live link you can check demo: https://regex101.com/r/u2uWGX/1
you can use ?
at end of group for optional group patterns:
its work fine: /(<imgs)[^>]*(src=S+)[^>]*(salt=["|'].*?["|'])?[^>]*(/?>)/gm
and here the live link you can check demo: https://regex101.com/r/u2uWGX/1
If you have a set of img
elements in your HTML. You can also get the src
and alt
value by looping a HTMLCollection
.
Demo :
const imgCollection = document.getElementsByTagName('img');
for (let item of imgCollection) {
console.log('src :', item.src)
console.log('alt :', item.alt)
}
<img src="https://example.com/image" alt="example1">
<img src="https://example.com/image">
I need to get from all the images the src and alt of the html code. I managed to get it but I have the following problem:
The following code works with problem:
https://regex101.com/r/3Vlkql/1
(<imgs)[^>]*(src=S+)[^>]*(salt=["|'].*?["|'])[^>]*(/?>)
Substitution:
$1$2$3$4
Result:
<img src="https://example.com/image" alt="example1">
Problem: My regex only detect if have src and alt. But if not have alt, the regex not detect me. How can I do with regex to get both?
This not match with regex:
<img src="https://example.com/image">
I dont have problem if i need to use 2 regex to get my purpose.
Don’t use regular expressions to parse HTML. Use a proper HTML parsing module.
This regex:]*balt=)[^>]*?> Match images that not have alt, but how can i group to get
only for this images that not contain alt –
You are starting to discover why you don’t want to parse HTML with regexes.
Have you watched the steps counter in regex101? This pattern already looks laborious. What if
But not work with: ]*balt=)[^>]*?> Match images that not have alt, but how can i group to get
only for this images that not contain alt
its work with
use this one
Can you check why dont work?