1

I have a string like this:

20 EQUALS 'Value goes here'

I want to split it up into 3 separate strings:

conditionField = 20 conditionOperation = 'EQUALS' conditionValue = 'Value goes here'

I tried this to get the Condition Field:

var conditionField = condition.replace(/(.*)(.*EQUALS)/, '$1');

But it get's the beginning and the end.

I'm having trouble splitting it up and dealing with the white space and spaces in the value.

9
  • 1
    Can you show us what you've tried? Commented Aug 21, 2017 at 5:04
  • You may try this /(\d*) (EQUALS) (\d*)/g Commented Aug 21, 2017 at 5:04
  • What are all possible inputs? Twenty LESS THAN '21' is this valid input? Commented Aug 21, 2017 at 5:07
  • @Tushar No, the conditionField will always be a number, the operation will never have a space Commented Aug 21, 2017 at 5:08
  • 1
    This should work then /^(\d+)\s+([a-z]+)\s+(.*)$/i. Use $1, $2 and $3 to get respective values. Commented Aug 21, 2017 at 5:10

2 Answers 2

1

Your question would actually be a bit of challenge if you wanted to arbitrarily extract quoted terms along with individual words. But since you appear to have a rather fixed structure, starting with a single number, then a single word command, followed by a third term, we can use the following regex pattern here:

([^\\s]*)\\s+([^\\s]*)\\s+(.*)

Each term in parentheses above will be made available as a capture group after the match has been run. In this case, I just blanket everything after the first two terms together.

var string = "20 EQUALS 'Value goes here'";

var re = new RegExp("([^\\s]*)\\s+([^\\s]*)\\s+(.*)");
match = re.exec(string);
if (match != null) {
    console.log(match[1])
    console.log(match[2])
    console.log(match[3])
}

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

3 Comments

I'll recommend using Regex Literal syntax. That way, you don't have to escape those backslashes.
@Tushar I'd be happy to edit if I even knew what that was :-) ... 100K doesn't mean I know everything.
Here's trick: Execute new RegExp("([^\\s]*)\\s+([^\\s]*)\\s+(.*)") in browser console and you'll get it. :)
0

Try this :

var data = '20 EQUALS 30'; var a = data.split(/(\d*) ([a-zA-Z]*) (\d*)/g); conditionField = a[1]; conditionOperation = a[2]; conditionValue = a[3];

1 Comment

Sorry, but "Try this :" + a chunk of code isn't terribly helpful to anyone.

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.