0

I have this values:

  • 4Green (Blister) [Others]
  • !@#$%^&*()'RWEW<>?P{}:" [Sachet]
  • TRIAL [Sachet]

How do I get the value inside [] only I don't need any other value. Just the string inside the [] part like Sachet or Others in javascript. I need them and Pass it to my ajax function

1
  • Use RegEx to fetch anything between []. Check the options for it being not-greedy (if it's what you're looking for) Commented Aug 18, 2015 at 2:59

3 Answers 3

2

Using a regular expression is the fastest way here; you can use this one: (\[\w+\])+ or (\[.*\]) or \[(.*?)].

UPDATE

var samples = [ '4Green (Blister) [Others]', '!@#$%^&*()\'RWEW<>?P{}:" [Sachet]',
    'TRIAL [Sachet]'];
var regex = /\[(.*?)]/;

for (var i = 0; i < samples.length; i++) {
  console.log(samples[i].match(regex)[1]);
}

Output:

machina@6PXM10I> node regex.js
Others
Sachet
Sachet
Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to use a regular expression for whatever reason, you can do it this way:

  1. You could obtain each string you want to test, perhaps with document.getElementsByClassName, and then cycle through the array-like Collection it returns to extract each string.

  2. Then, use the "indexOf()" method to find the start and end of each bracket. Here's more info on "indexOf()" http://www.w3schools.com/jsref/jsref_indexof.asp

  3. Once you have the start and end of each bracket, use the substring method to extract the contents of the brackets. More info on the substring method here: http://www.w3schools.com/jsref/jsref_substring.asp

The end result would look something like this:

        var myStrings = document.getElementsByClassName("classNameHere");
        for(var i = 0; i < myStrings.length; i++){
            var start = myStrings[i].indexOf("[");
            var end = myStrings[i].indexOf("]");
            var extractedString = myStrings[i].substring(start, end);
            // Do your Ajax call here with the "extractedString" variable
        }

Comments

1

You can do the following:

var myString = "TRIAL [Sachet]";

var myRegexp = /\[(.*)\]+/g;
var match = myRegexp.exec(myString);
alert(match[1]);

That regex will get you anything inside the [].

One more thing for you to not is !@#$%^&*()'RWEW<>?P{}:" [Sachet] invalid string and you will need to escape the quotes.

!@#$%^&*()'RWEW<>?P{}:\" [Sachet]

Note the \ before "

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.