culter
culter

Reputation: 5697

How to filter out special character in javascript

I have this javascript (JSFiddle below):

$(document).ready(function() {
var table = $('#example').DataTable();

$('input[type="checkbox"]').on('change', function() {
  console.log($(this).attr("id"), this.checked)
  var choosedString = "";
  if ($('#A').prop('checked')) {
    choosedString = "A"
  }
  if ($('#Aplus').prop('checked')) {
  choosedString += choosedString.length > 0 ? "|" : "";
  choosedString += "A\\+"
  }

console.log(table)
table.column(3).search(choosedString,  true, false).draw();

  });

});

Here is JSFIDDLE

I need to select 'A' and/or 'A+' values from the table via the 2 checkboxes. I figured out how to select 'A+', but when I'm trying to choose 'A', also the A+ are included in the selection. How to filter out the special character? Thank you.

Upvotes: 0

Views: 272

Answers (3)

Harry baldaniya
Harry baldaniya

Reputation: 167

you need to change this line

table.column(3).search(choosedString,  true, false).draw();

to

table.column(3).search("^" + choosedString + "$", true, false).draw();

then you can filter table by exact match A OR A+.You can see demo here

Upvotes: 1

Takit Isy
Takit Isy

Reputation: 10081

You can use ^ and $ anchors to match the start and end of the string:

$(document).ready(function() {
  var table = $('#example').DataTable();

  $('input[type="checkbox"]').on('change', function() {
    console.log($(this).attr("id"), this.checked)
    var choosedString = "";
    if ($('#A').prop('checked')) {
      choosedString = "^A$"; // Modified here
    }
    if ($('#Aplus').prop('checked')) {
      choosedString += choosedString.length > 0 ? "|" : "";
      choosedString += "A\\+"
    }
    console.log(table)
    table.column(3).search(choosedString,  true, false).draw();

  });

});

Working fiddle (using only $): https://jsfiddle.net/10uhwapv/96/

Hope it helps.

Upvotes: 2

C3roe
C3roe

Reputation: 96417

You are using the regular expression mode of the search method here already - but the problem with that is, that A as a “regular expression” of course still matches anything that contains an A anywhere, and doesn’t limit it any further.

If you anchor these expressions at the start and end using ^ and $, you should be able to get what you want:

if ($('#A').prop('checked')) {
  choosedString = "^A$"
}
if ($('#Aplus').prop('checked')) {
  choosedString += choosedString.length > 0 ? "|" : "";
  choosedString += "^A\\+$"
}

https://jsfiddle.net/10uhwapv/102/

Upvotes: 2

Related Questions