Reputation: 4357
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
Reputation: 12045
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
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