5

this drives me nuts - Im trying to remove all white-spaces in a string, and nothing seems to work. what am i doing wrong?

This is what im trying with at the moment:

$(".unfoldedlabel a").text().replace(/ /g,'');

HTML:

<span class="unfoldedlabel" colspan="6"><a>Accessories/Service & Support</a></span>

3 Answers 3

9

You're not updating the text in HTML. After removing the spaces, the innerText in DOM need to be updated.

Use .text(function):

$(".unfoldedlabel a").text(function (index, oldText) {
    return oldText.replace(/\s+/g, '');
});

$(".unfoldedlabel a").text(function(i, t) {
  return t.replace(/\s+/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class="unfoldedlabel" colspan="6"><a>Accessories/Service & Support</a></span>

Sign up to request clarification or add additional context in comments.

2 Comments

I'm nitpicking here but to remove "all whitespaces" the regex should probably be /\s/g instead :)
@Andreas Yes, used \s+ to replace all spaces
1

And another solution is:

var s=$(".unfoldedlabel a").text();
$(".unfoldedlabel a").text(s.replace(/ +?/g, ''));//or /\s+?/g

Comments

0

You can use this code -

$(function() {
  var changeText = $(".unfoldedlabel a").text().replace(/ /g,'');

  $(".unfoldedlabel a").text(changeText);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.