blueren blueren - 9 days ago 7
Javascript Question

Matching a JS string with regex

I have a long xml raw message that is being stored in a string format. A sample is as below.

<tag1>val</tag><tag2>val</tag2><tagSomeNameXYZ/>


I'm looking to search this string and find out if it contains an empty html tag such as
<tagSomeNameXYZ/>
. This thing is, the value of SomeName can change depending on context. I've tried using
Str.match(/tagSomeNameXYZ/g)
and
Str.match(/<tag.*.XYZ\/>/g)
to find out if it contains exactly that string, but am able to get it return anything. I'm having trouble in writing a reg ex that matches something like
<tag*XYZ/>
, where
*
is going to be
SomeName
(which I'm not interested in)

Tl;dr : How do I filter out
<tagSomeNameXYZ/>
from the string. Format being :
<constant variableName constant/>


Example patterns that it should match:

<tagGetIndexXYZ/>
<tagGetAllIndexXYZ/>
<tagGetFooterXYZ/>

Answer

The issue you have with Str.match(/<tag.*.XYZ\/>/g) is the .* takes everything it sees and does not stop at the XYZ as you wish. So you need to find a way to stop (e.g. the [^/]* means keep taking until you find a /) and then work back from there (the slice).

Does this help

testString = "<tagGetIndexXYZ/>"
res = testString.match(/<tag([^/]*)\/\>/)[1].slice(0,-3)
console.log(res)