我想要替換所有的空格,但不希望替換字符串末尾的空格。 例如我的問題:今天替換所有的空白,但除了空白末尾
是一個悲哀的日子
今天是-A-悲傷 - 日
str = "today is a sad day ";
newstr = str.replace(/\s/g,"-");
我想要替換所有的空格,但不希望替換字符串末尾的空格。 例如我的問題:今天替換所有的空白,但除了空白末尾
是一個悲哀的日子
今天是-A-悲傷 - 日
str = "today is a sad day ";
newstr = str.replace(/\s/g,"-");
試試這個代碼trim();
str = "today is a sad day ";
str = str.trim();
newstr = str.replace(/\s/g,"-");
alert(newstr);
您需要使用trim()
從兩個刪除空白字符串的兩面:
str = "today is a sad day ";
console.log(str.trim().replace(/\s/g, "-"))
只是一個警告,['String#trim()'](https://developer.mozilla。如果需要,org/en/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Browser_compatibility)在IE8中不可用。 – Phylogenesis
'不希望替換字符串末尾的空白字符',所以我認爲'trim'的做法相反 – Justinas
簡單地split(" ")
做字符串空間,然後join('-')
注意 *:對多餘的空格刪除
trim()
函數
console.log('today is a sad day '.trim().split(" ").join('-'))
OP例子在'day'之後有一個空格,就像'今天是一個悲傷的日子' –
str = "today is a sad day ";
newstr = str.replace(/\s(?!$)/g,"-");
你最好解釋一下你的解決方案,而不是簡單的張貼一些代碼。也許值得一讀[如何寫出一個好答案](https://stackoverflow.com/help/how-to-answer)。 –
也許你想做到這一點?
str = "today is a sad day ";
toReplace = str.substring(0, str.length-1);
newstr = toReplace.replace(/\s/g,"-");
replaced = newstr + " ";
console.log(replaced);
隨着String.prototype.replace()可以使用function (replacement)
來創建新的子被用於替換匹配給定的正則表達式。提供給該功能的參數在「Specifying a function as a parameter」中描述。
比你可以使用字符串的長度和當前offset
返回匹配或所需的替換'-'
。
代碼:
var str = 'today is a sad day ';
var result = str.replace(/\s/g, function(match, offset, string) {
return string.length - 1 !== offset ? '-' : match;
});
console.log(result);
[?刪除所有出現,除了最後](// stackoverflow.com/q/9694930) – Tushar
使用修剪第一,刪除空格。 –
所以你想保留空白字符串結束? – Justinas