简体   繁体   English

javascript正则表达式用连字符替换空格

[英]javascript regex to replace space with a hyphen

I need a regex which should read a string : 我需要一个正则表达式,它应该读取一个字符串:

  1. with a 1 to unlimited numbers (say upto 10) 从1到无限的数字(例如最多10)
  2. read a space in between 阅读之间的空格
  3. with a 1 to unliimited numbers (say upto 10) 带有1到无限制的数字(例如最多10个)

then replace the space in the string with a '-' 然后用'-'替换字符串中的空格

for ex: 123 456 should be replaced with 123-456. 例如:123 456应替换为123-456。

there are no any other characters apart from numbers in the string. 字符串中除数字外没有其他字符。

Try this: 尝试这个:

'123 456'.replace(/ /g, '-')
// "123-456"

If you need to replace spaces only in strings that match "(digits)(space)(digits)" patterns - use lookaheads. 如果只需要在匹配“(数字)(空格)(数字)”模式的字符串中替换空格,请使用先行符。 Unfortunately, JS doesn't support lookbehinds: 不幸的是,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"

To use the pattern inside a string: 要在字符串中使用模式:

 "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"

It seems you look for something called backreferences . 看来您正在寻找一种称为反向引用的东西。

When your search string would be: 当您的搜索字符串是:

"([0-9]{1,10}) ([0-9]{1,10})"

your replacement string would be something like: 您的替换字符串将类似于:

"\1-\2"

To match only rows where your pattern and only your pattern matches add line anchors "^" (beginning of line) and "$" (end of line), so your pattern would look like: 要仅匹配模式和仅模式匹配的行,请添加行锚 “ ^”(行的开头)和“ $”(行的末尾),因此您的模式应如下所示:

"^([0-9]{1,10}) ([0-9]{1,10})$"
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)

Output: 输出:

'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

This regex will handle all scenarios you need with no limitation on numbers. 此正则表达式将处理您需要的所有情况,而数量不受限制。

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

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