正则表达式替换的比我想要的更多

Regex replacing more than I want

本文关键字:我想要 替换 正则表达式      更新时间:2023-09-26

我想从body元素中删除一个以demo-XXX开头的类,其中xxx可以是任何字符并且没有固定长度。

所以我可以在身体里有这样的东西

<body classs="bye demo-hello water">

我像这样使用这个正则表达式/'b's?demo-.*'b/g

$("body")[0].className = $("body")[0].className.replace(/'b's?demo-.*'b/g, '');

但它也删除了demo-XXX之后的所有类,例如water

<body classs="bye">

你可以按照@nhahtdh所说的方式简单地做到这一点

$('body').attr('class', function(_, cls){
   return cls.split(/'s+/).filter(function(x){  // split
       return x.indexOf("demo-") !== 0; // filter out unwanted values
   }).join(" "); // join the array and return it
});

如果你想要正则表达式解决方案,你可以做

$('body').attr('class', function(_, cls){
   return cls.replace(/'bdemo-'S+/g,"");
});
您需要

排除空格 usintg ^'s并查找 1 个或多个字符,因此请使用 + 而不是*

$("body")[0].className =$("body")[0].className.replace(/'b's?demo-[^'s]+'b/g,'');

演示

'b's?demo-[a-zA-Z0-9]+'b

使用这个。.将在'b之前消耗掉所有.