Javascript How to use regex for json string to find data column in jQuery?

I just used the below instruction in javascript to search for a specific row in one column and filter the records in the data table.

term = $(this).val(); table.column(2).search(term, true, false).draw(); 

Here is my JSON line:

 [{"userid":"2315","location":"x","details":"{\"subjectβ€Œβ€‹s\": {\"English\": [\"meena\", \"teena\"]}, \"hours\": {\"2\"}}}", {"userid":"3009","location":"y","details":"{\"subjects\": {\"English\": [\"meena\"]}, \"hours\": {\"4\"}}}, {"userid":"3109","location":"z","details":"{\"English\": [\"suresh\", \"divya\"]}, \"hours\": {\"4\"}}, {"userid":"3209","location":"a","details":"{\"English\": [\"ramesh\", \"meena\"]}, \"hours\": {\"4\"}}, {"userid":"3309","location":"b","details":"{\"subjects\": {\"English\": [\"revathi\", \"meena\"]}, \"hours\": {\"4\"}}} ] 

Want to match any "English" value with a regular expression and search with these values ​​to filter records. Something like below.

 regex = '"English": ["'+ '.*' +term+'.*'; table.column(3).search(regex, false, false).draw(); 

But the above statement does not work.

Can someone suggest me the correct way to write regex for this?

+6
source share
1 answer
  • If the search method supports regular expressions and you absolutely need to do such things, pass something like new RegExp('"English": \\["'+ '.*' +term+'.*', 'gi') .

  • As suggested in the comments, a great idea is to treat JSON as a string. Excessive spaces or escaped special characters can lead to incorrect answers. You would be better off parsing JSON and searching as necessary, for example:

     var term = ...; for (var i = 0, l = rows.length; i < l; i++) { var row = rows[i]; var user = JSON.parse(row); var details = user.details && JSON.parse(user.details); if (details.English && details.English.indexOf(term) !== -1) { // there is the searched term in the users' details } } 
0
source

All Articles