用‘+‘替换字符串中的所有空格[复制]

本文翻译自:Replace all spaces in a string with '+' [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

I have a string that contains multiple spaces. 我有一个包含多个空格的字符串。 I want to replace these with a plus symbol. 我想用加号替换它们。 I thought I could use 我以为我可以用

var str = 'a b c';
var replaced = str.replace(' ', '+');

but it only replaces the first occurrence. 但它只取代了第一次出现。 How can I get it replace all occurrences? 如何让它替换所有出现的?


#1楼

参考:https://stackoom.com/question/FvEN/用-替换字符串中的所有空格-复制


#2楼

Do this recursively: 递归地执行此操作:

public String replaceSpace(String s){
    if (s.length() < 2) {
        if(s.equals(" "))
            return "+";
        else
            return s;
    }
    if (s.charAt(0) == ' ')
        return "+" + replaceSpace(s.substring(1));
    else
        return s.substring(0, 1) + replaceSpace(s.substring(1));
}

#3楼

Use global search in the string. 在字符串中使用全局搜索。 g flag g标志

str.replace(/\s+/g, '+');

source: replaceAll function source: replaceAll函数


#4楼

NON BREAKING SPACE ISSUE 不破坏空间问题

In some browsers 在某些浏览器中

(MSIE "as usually" ;-)) (MSIE“通常”;-))

replacing space in string ignores the non-breaking space (the 160 char code). 替换字符串中的空格会忽略不间断的空格(160字符代码)。

One should always replace like this: 一个人应该总是这样替换:

myString.replace(/[ \u00A0]/, myReplaceString)

Very nice detailed explanation: 很好的详细解释:

http://www.adamkoch.com/2009/07/25/white-space-and-character-160/ http://www.adamkoch.com/2009/07/25/white-space-and-character-160/


#5楼

You can also do it like 你也可以这样做

str = str.replace(/\s/g, "+");

Have a look to the fiddle 看看小提琴


#6楼

You need the /g (global) option, like this: 你需要/g (全局)选项,如下所示:

var replaced = str.replace(/ /g, '+');

You can give it a try here . 你可以在这里尝试一下 Unlike most other languages, JavaScript, by default, only replaces the first occurrence. 与大多数其他语言不同,默认情况下,JavaScript仅替换第一次出现的语言。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值