Neda Homa
Neda Homa

Reputation: 4357

Remove spaces at the end of class attribute

I want to remove the spaces at the end of the class attribute in this string:

<div class="test  wrapper   " id="test"> " sample text " </div>

If I use

text = text.replace(/\s+"/g, '"');

then the space after sample text also will be removed and I want to keep that space.

Do you have any idea how can I do this?

Upvotes: 2

Views: 151

Answers (2)

gfullam
gfullam

Reputation: 12045

Make your regex more specific

By adding class=" to your regular expression, you can narrow the scope of the replacement. Then using a capturing group () and the $n replacement pattern, you can save just the list of class names excluding any spaces:

var text = '<div class="test  wrapper   " id="test"> " sample test " </div>';
text = text.replace(/class="\s*(.+?)\s*"/g, 'class="$1"');
alert(text);

Upvotes: 2

jatinder bhola
jatinder bhola

Reputation: 385

if you want result which looks like
"sample test"
then use this code with js:

var str = " sample test ";
var newStr = str.trim();
// "sample test"

and with js and regular expression:
use this code:

var str = " sample test ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "sample test"

Upvotes: -1

Related Questions