简体   繁体   English

如何在字符串替换中包含空格?

[英]How to include whitespaces in string replace?

I need to replace strings like '5 hours' with '5h'. 我需要将“ 5小时”之类的字符串替换为“ 5h”。 But I'm only able to get it to '5 h'. 但是我只能将其设置为“ 5小时”。 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'. 当我用空格将函数中的“ hours”替换为“ hours”时,它什么也不会替换并返回“ 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 . 这将替换前导空格以及字符串hours以字符串h

Working JSFiddle Example: https://jsfiddle.net/4bqz79vh/ 工作的JSFiddle示例: https ://jsfiddle.net/4bqz79vh/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM