Subhan
Subhan

Reputation: 1634

Javascript adding variable to a regular expression

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?

Upvotes: 0

Views: 230

Answers (1)

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

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 ;].

Upvotes: 2

Related Questions