[英]javascript regex to replace space with a hyphen
我需要一個正則表達式,它應該讀取一個字符串:
然后用'-'替換字符串中的空格
例如:123 456應替換為123-456。
字符串中除數字外沒有其他字符。
嘗試這個:
'123 456'.replace(/ /g, '-')
// "123-456"
如果只需要在匹配“(數字)(空格)(數字)”模式的字符串中替換空格,請使用先行符。 不幸的是,JS不支持lookbehinds:
'123 456'.replace(/(^\d+) (?=\d+$)/, "\$1-")
// "123-456"
'A123 456'.replace(/(^\d+) (?=\d+$)/, "\$1-")
// "A123 456"
'123 456 324'.replace(/(^\d+) (?=\d+$)/, "\$1-")
// "123 456 324"
要在字符串中使用模式:
"Shop U5, 124 134 Millers Road".replace(/(\b\d+) (?=\d+\b)/, "\$1-")
// "Shop U5, 124-134 Millers Road"
"124 134 Millers Road".replace(/(\b\d+) (?=\d+\b)/, "\$1-")
// "124-134 Millers Road"
"124 134".replace(/(\b\d+) (?=\d+\b)/, "\$1-")
// "124-134"
var str = 'Shop U5, 124 134 Millers Road';
var regex = /(.*\d{1,10})\s(\d{1,10}.*)/;
if (str.match(regex)) {
str = str.replace(regex, "$1" + "-" + "$2");
}
alert(str)
輸出:
'Shop U5, 124-134 Millers Road'
var str = "123 456 7891 2";
var regex = /(\d+)\s(\d+)/g;
while( str.match(regex) ) {
str = str.replace(regex, "$1-$2");
}
alert(str); // Result 123-456-7891-2
此正則表達式將處理您需要的所有情況,而數量不受限制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.