Alvaro
Alvaro

Reputation: 41595

Regex replacing more than I want

I want to delete from the body element only one class which starts with demo-XXX where xxx can be any character and without a fix length.

So I can have something like this in the body

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

I was using this regex /\b\s?demo-.*\b/g like so:

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

But it is removing as well all the classes after demo-XXX, such as water:

<body classs="bye">

Upvotes: 0

Views: 60

Answers (3)

Amit Joki
Amit Joki

Reputation: 59232

You can simply do it this way as said by @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
});

If you want regex solution, you could do

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

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You need to exclude space usintg ^\s and look for 1 or more characters so use + instead of *

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

DEMO

Upvotes: 1

vks
vks

Reputation: 67968

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

Use this.. will consume all before detecing \b.

Upvotes: 0

Related Questions