Kaiusee
Kaiusee

Reputation: 1333

RegEx in JavaScript - Start with and Ends with

I want to extract a string using RegEx in Javascript for example

StudentName nameX = John; 

or

StudentName nameX;

I want to extract only "nameX" this is what i've tried so far.

var name = allName.match("StudentName(.*);|StudentName(.*)=");

what I'm getting is : "nameX = John" , but I'm not getting "nameX" only.

Upvotes: 1

Views: 141

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

Try this non greedy pattern

var name = allName.match("StudentName\\s*(.*?)\\s*[=;]");

JSFiddle Demo

Upvotes: 2

Ωmega
Ωmega

Reputation: 43663

Use regex pattern inside of match

match(/StudentName\s+(\w+)/)[1]

See this demo.​​

Upvotes: 2

Bruno
Bruno

Reputation: 5822

If you split on blank spaces then the second match at index 1 should contain the name.

var name = allName.split(/[ ;]/g)[1];

Upvotes: 1

Related Questions