1

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.

3 Answers 3

2

Use regex pattern inside of match

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

See this demo.​​

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

2 Comments

Thanks, that works. is there a way to find all the objects? for example, if you have StudentName nameX; StudentName nameY; StudentName nameZ; can you find all of nameX,y and z ? Thanks
@kkDev - To find all occurrences use re = new RegExp() and while loop with match = re.exec() condition. Google for it :)
2

Try this non greedy pattern

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

JSFiddle Demo

Comments

1

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

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

Comments

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.