sm1l3y sm1l3y - 21 days ago 6
Javascript Question

Regex doesn't work correctly

I am having some challenges getting a regex to work correctly.

Basically I need to replace this ":TABLE COUNT #" from a string. # being a number from 0-9.

Here is my code:

$("#tbl").each(function() {
var x = $(this).text();
var y = x.replace(":TABLE COUNT " + /[0-9]/, "");
$(this).html(y);
})


Here is my jsFiddle

Answer

Try using a regexp as the first parameter of the .replace() method instead a string.

Replace() documentation

By the way, the id attribute should be unique. I replaced id attributes by class.

$(".tbl").each(function() {
  var x = $(this).text();
  var y = x.replace(/:TABLE COUNT \d/, "");
  $(this).html(y);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="tbl">
  TABLE:TABLE COUNT 3
</p>
<p class="tbl">
  4-WAY
</p>
<p class="tbl">
  TABLE:TABLE COUNT 5
</p>
<p class="tbl">
  TABLE:TABLE COUNT 9
</p>
<p class="tbl">
  4-WAY
</p>

/:TABLE COUNT \d/means :

Contains this string :TABLE COUNT followed by a digit character \d

\d: Matches a digit character in the basic Latin alphabet. Equivalent to [0-9].

RegExp documentation