0

Consider this code:

var myregexp = "\\*(.+)"; // set from another subsystem, that's why I'm not using a literal regexp
var input = "Paypal *Steam Games";
var output = input.match(new RegExp(myregexp, 'gi'), "$1");

The output is ["*Steam Games"], but I would like it to be just ["Steam Games"].

What is wrong?

PS A great resource I found today: http://regex101.com/#javascript

1
  • Is the regular expression only intended to match "Steam Games", or is it intended to match other strings as well? Commented Mar 9, 2014 at 19:46

2 Answers 2

2

match doesn’t accept a second argument.

Since you have the global flag set (and I assume it’s intentional), you’ll need exec to find all of the first groups:

var m;

while ((m = re.exec(input)) {
    alert(m[1]); // Get group 1
}
Sign up to request clarification or add additional context in comments.

Comments

1
var str = "Paypal *Steam Games";

var reg = /\w+\s?\*(\w+\s?\w+)/; // or your exp will work too `/\*(.+)/;`

console.log(reg.exec(str)[1]); // result Steam Games

JSFiddle

You'll get Steam Games from your string with help of /\w+\s?\*(\w+\s?\w+)/ exp

In JavaScript there are three main RegExp functions:

exec A RegExp method that executes a search for a match in a string. It returns an array of information.

match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.

test A RegExp method that tests for a match in a string. It returns true or false.

7 Comments

please explain your answers
I did explain. No matter how trivial, even if YOU think it's redundant, code dump answers are bad answers in my opinion.
@RUJordan Also provided JSFiddle example, what else do you want ?
Code is not an explanation. Words are explanations. Just because it makes sense to you doesn't mean the rest of the world will get it, and those few words can help future googlers. Also, saying "no offense" before something just insinuates offense. You're kind of lucky people didn't downvote you for that alone.
I haven't ever down voted because of explanation, if someone claims and writes code ( and is a bit on programming world ), will understand everything from my posts. When it is necessary I am explaining. If OP can't understand, I am doing my best to advice him and show the way
|

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.