Reputation: 331
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");
});
Upvotes: 0
Views: 56
Reputation: 834
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/
Upvotes: 2
Reputation: 146302
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
Upvotes: 3