1

I use regex to query all square brackets in string by this command:

var sizecolor = textvalue.match(/[^[\]]+(?=])/g);

I want to get a square bracket in object above if it contain "SPrice";

Example: I have string like this:

"I have two square brackets are `[Apple = Red, Cool, Sweet]` and `[Check+SPrice = Cheap, Expensive, Comfortable]`"

How can I returns this [Check+SPrice = Cheap, Expensive, Comfortable] because it contains SPrice

Thanks.

4
  • You could just return indexOf Sprice. Then iterate backwards, until you get the first square bracket, likewise for the last and then cut the string at those indexes? Commented Aug 24, 2018 at 14:57
  • Hi @SeanT How can I use indexOf to return array I want ? Commented Aug 24, 2018 at 14:58
  • 1
    Try /\[([^[\]]*SPrice[^[\]]*)]/.exec(s)[0] (or [1], not sure what you need) Commented Aug 24, 2018 at 14:59
  • Can you please update to answer? I will check and give the best. Commented Aug 24, 2018 at 15:00

1 Answer 1

1

You may use

/\[[^[\]]*SPrice[^[\]]*]/g

See the regex demo

Details

  • \[ - a [ char
  • [^[\]]* - 0+ chars other than [ and ]
  • SPrice - a SPrice substring
  • [^[\]]* - 0+ chars other than [ and ]
  • ] - a ] char.

JS Demo:

var rx = /\[[^[\]]*SPrice[^[\]]*]/g;
var str = "I have two square brackets are [Apple = Red, Cool, Sweet] and [Check+SPrice = Cheap, Expensive, Comfortable]";
console.log(str.match(rx));

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

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.