简体   繁体   English

正则表达式无法正常工作

[英]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. 基本上,我需要从字符串中替换此“:TABLE COUNT#”。 # being a number from 0-9. #是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 这是我的jsFiddle

Try using a regexp as the first parameter of the .replace() method instead a string . 尝试使用regexp作为.replace()方法的第一个参数,而不是string

Replace() documentation Replace()文档

By the way, the id attribute should be unique. 顺便说一句, id属性应该是唯一的。 I replaced id attributes by class . 我用class代替了id属性。

 $(".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 : /:TABLE COUNT \\d/表示:

Contains this string :TABLE COUNT followed by a digit character \\d 包含以下字符串:TABLE COUNT后跟数字字符\\d

\\d : Matches a digit character in the basic Latin alphabet. \\d :匹配基本拉丁字母中的数字字符。 Equivalent to [0-9]. 相当于[0-9]。

RegExp documentation RegExp文档

switch from id's to classes, then do something like this: 从id切换到类,然后执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM