0

I need to replace strings like '5 hours' with '5h'. But I'm only able to get it to '5 h'. How to remove the space in between? When I replace the "hours" in my function to " hours" with a whitespace, it replaces nothing and returns '5 hours'.

$('div.block_name span').text(function(){
    return $(this).text().replace("hours","h");
});
1
  • Show your HTML. Commented Jul 25, 2017 at 14:26

2 Answers 2

3

You can use regex like so:

// "\s?" means that find a space only if it exists
console.log("5 hours".replace(/\s?hours/, 'h')); // 5h
console.log("5hours".replace(/\s?hours/, 'h')); // 5h

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

6 Comments

This solution also works with non-breaking spaces ( ), which get translated to unicode character 160 by jQuery's text() method. I believe that's what the OP's issue was.
Yeah! Thanks for the regex method. I tried using it earlier but was using the putting quotes around it. Btw, jquery just made the world look easier for me. (just started using it today!)
@VaishMK I would suggest not using jquery. You can use DOM node .textContent
But happy to help! :-)
Most definitely.
|
2

Try this:

$('div.block_name span').text(function(){
                    return $(this).text().replace(" hours","h");
                });

This will replace the leading whitespace as well as the string hours with the string h.

Working JSFiddle Example: https://jsfiddle.net/4bqz79vh/

2 Comments

Just tested on this fiddle and it works as expected: jsfiddle.net/4bqz79vh
The regex solution should work. If there is a non-breaking space ( ) in the HTML markup, it gets translated to unicode character 160 instead of a standard space.

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.