kellzerIrl
kellzerIrl

Reputation: 101

Issue with regex in javascript?

I'm using regex in javascript to check if a string contains a tag called 'tag-name'. See below:

    someText
    <other>more text<other>
</tag-name>

I want to extract "tag-name", only if it occurs following the first instance of '<' in the string. So in the example above, my regex should not find a match as there is a '<' character at the 'other' tag.

In this example below, it should return 'tag-name' as it occurs after the first occurance of '<'.

someText
</tag-name>
<other></other>

Can anyone suggest how I can get this to work, so far I have used this expression:

<*?tag-name

but, it is extracting the tag-name string regardless of where it occurs.

Thanks for your help.

Upvotes: 1

Views: 48

Answers (1)

elixenide
elixenide

Reputation: 44823

You can use this regex:

/^[^<]*<[^<]*tag-name/

The logic is to match the start of the string, zero or more non-< characters, <, zero or more non-< characters, then your tag name.

Demo — Be sure to see the Unit Tests (link on the lower left) to demonstrate both of your cases.

Upvotes: 1

Related Questions