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");
});
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
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.