How to search the text between the HTML tags

Viewed 861

I'm using mongoJS to process my database query. I came across an issue which the string contains HTML tags, I'm using regex expressions to search my string in the collection. How to search the text by ignore the HTML tags?

var userInput = $scope.userInput; // value from user input
db.collections.find({'obj': {$regex: new RegExp(userInput) } }).toArray(function(err, result){ 
  return res.json(result); 
}

Collections

[{_id:"34aw34d343s4", obj:"How are you?"},
{_id:"34asdfwer343s4", obj:"Are you okay?"},
{_id:"3sDaweqr43s4", obj:"Goodbye, my friend!"},
{_id:"34aw3sdfgds3s4", obj:"Do you know these are <strong>important</strong> items"}]

User Input

these are
these
these are important

Output

[{_id:"34aw3sdfgds3s4", obj:"Do you know these are <strong>important</strong> items"}]
[{_id:"34aw3sdfgds3s4", obj:"Do you know these are <strong>important</strong> items"}]
[]

Expected

[{_id:"34aw3sdfgds3s4", obj:"Do you know these are <strong>important</strong> items"}]
[{_id:"34aw3sdfgds3s4", obj:"Do you know these are <strong>important</strong> items"}]
[{_id:"34aw3sdfgds3s4", obj:"Do you know these are <strong>important</strong> items"}]
3 Answers

You should sanitize the user input before it goes into the database. From my understanding of your system, there is a great probability that user input (prior to being inserted in the database)is not sanitized and your site is vulnerable to an XSS attack.

I recommend you to use a library like sanitize-html to secure your site against cross-site scripting and as well as an answer to this question.

You could use the RegExp test method: /these|are/.test(stringToCheckAgainst);

var testCases = ["these are", "these", "these are <strong>item</strong>"];

testCases.forEach(function(value) {
  document.write(/these|are/.test(value) + "\n");
});

If you want to remove the html tag then the following method

  1. jQuery(html).text();
  2. yourStr.replace(/<(?:.|\n)*?>/gm, '');
  3. yourStr.replace(/<[^>]+>/g, '');

more on Strip HTML from Text JavaScript

Related