简体   繁体   中英

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)
  2. read a space in between
  3. with a 1 to unliimited numbers (say upto 10)

then replace the space in the string with a '-'

for ex: 123 456 should be replaced with 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:

'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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