0

I've written the following function in Typescript:

public searchPosts(keyword ? : string): Post[] {
  return this._posts.filter(function(post) {
    if (post.title.search(new RegExp('money', 'gi')) >= 0) {
      return post;
    }
  });
}

It's working just fine but, I need to make it a little dynamic so that instead of hardcoded value i.e. money, I can put my keyword variable in RegExp (new RegExp(keyword, 'gi')). But doing so does not return anything even for 'money' as a keyword.

Any ideas on what I'm doing wrong here?

9
  • Replace 'gi' with keyword? --- Hmm. Commented Jul 5, 2017 at 9:50
  • 1
    Why are you returning the post in the filter? I got it to work using ES6 (keyword = '') => this._posts.filter(post => post.title.search(new RegExp(keyword, 'gi')) >= 0) Commented Jul 5, 2017 at 9:53
  • replacing did not work. I'm returning post that matches the criteria? Commented Jul 5, 2017 at 9:55
  • the filter should return true or false Commented Jul 5, 2017 at 9:55
  • I believe filter function: Returns the elements of an array that meet the condition specified in a callback function. Commented Jul 5, 2017 at 9:56

1 Answer 1

2

This is how it should work

  var keyword = '345';
  var f = ['1234', '3456'].filter(function(post) {
    return (post.search(new RegExp(keyword, 'gi')) >= 0);
  });
  
  console.log(f);

This is your function in pure JS

var posts = [{title: '1234'}, {title: '3456'}];

function searchPosts (keyword) {
  return posts.filter(function(post) {
    return (post.title.search(new RegExp(keyword, 'gi')) >= 0);
  });
}

console.log(searchPosts('345'));

If this doesnt work, the problem is somewhere else ;].

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

3 Comments

public searchPosts(keyword?: string): Post[] { return this._posts.filter(function(post) { return (post.title.search(new RegExp(keyword, 'gi')) >= 0); }); } What am I missing here?
public searchPosts(keyword?: string): Post[] { return this._posts.filter(function(post) { return (post.title.search(new RegExp('money', 'gi')) >= 0); }); } this gives me the desired result but as soon as I replace the search string with keyword it does not work. Even console.log for keyword is as expected. :/
I've edited my answer. Your function seems OK. As you can see in my answer when you provide a string to the function it returns the desired result, so it is working just fine. That's what I can help you with. If you provide the code in the Plunker, can try more.

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.