1

I want to be able to check and see which keys start with the letters "gra" and only return that content. I've tried a few things with the code below. In one approach I added something like {key.match(/gra/g)} in the return html but it is not very efficient (and still outputs blank content). I've also tried adding something like this:

  if(String(this.props.profile[key]).match(/gra/g)))

also tried:

  if(this.props.profile[key].match(/gra/g))

but keep getting errors like ".match" is not a function or can't read undefined, etc. I've tried various other ways but can't seem to get it working right.

   var grapes = Object.keys(this.props.profile).map(function(key) {
        if(this.props.profile[key] !=null) {
                return (
                     <li key={key} className="example-class">
                         <label>{key}:</label>{ this.props.profile[key] }
                      </li>
                  );
              }
    }, this);


    <html>
       {grapes}
    </html>

So, all that to say, what is the best way to filter using regex for something like this?

1 Answer 1

2

Why not just filter the array

var grapes = Object.keys(this.props.profile)
                   .filter(function(key) {
                       return key && key.toLowerCase().indexOf('gra') === 0;
                   })
                   .map(function(key) {
                       return (
                         <li key={key} className="example-class">
                             <label>{key}:</label>{ this.props.profile[key] }
                         </li>
                       );
                   }, this);
Sign up to request clarification or add additional context in comments.

11 Comments

hmm yeah hadn't thought of that. is "indexOf" similar to a .match()? just curious. thanks
indexOf is not similar to match, but it does look for strings in strings, so str.indexOf('gra') === 0 is true if the string starts with gra
A regex is better if you need case-insensitive check.
If you just want the first one, you don't really have to map them, just shift of the first one, something like this -> jsfiddle.net/kvbfnrb7
Anything is possible, something like this then -> jsfiddle.net/kvbfnrb7/2
|

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.