2

I want to replace the hyphen between 2 characters in a string. The 2 characters can be anything but a space.

string.replace(/regex/g, '');

so

  • dog-cat : dogcat
  • dog - cat : unchanged
  • 1-1 : 11
  • 1 - 1 : unchanged
  • $-$ : $$
  • $ - $ : unchanged
  • ^-^ : ^^
  • ^ - ^ : unchanged
  • etc...
2

3 Answers 3

1

You can use this regex replace:

str = str.replace(/(\S)-(\S)/g, '$1$2'); 

RegEx Demo

Here (\S)-(\S) matches a non-space character followed by hyphen followed by another non-space character. We are also capturing both adjacent characters in group and then in replacement we put back $1$2.

const regex = /(\S)-(\S)/g;
const str = `dog-cat
dog - cat
1-1
1 - 1
$-$
$ - $
^-^
^ - ^`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, '$1$2');

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

To remove all - chars in between non-whitespace chars you should use

.replace(/(\S)-(?=\S)/g, '$1')

See the regex demo.

Here,

  • (\S) - maches and captures any non-whitespace char into Group 1
  • - - a hyphen
  • (?=\S) - (a positive lookahead assuring that) after the hyphen, there must be a char other than a whitespace. This char is not consumed, i.e. the regex index stays right before it, allowing to match that char with the next iteration (as g global modifier will allow matching all occurrences of a regex pattern in a string).

JS demo:

var rx = /(\S)-(?=\S)/g;
var s = "dog-cat\ndog - cat\n1-1\n1 - 1\n$-$\n$ - $\n^-^\n^ - ^\n1-1-1-1";
console.log(s.replace(rx, '$1'));

Comments

-1

try this regex: "dog-cat".replace(/(?=\S)(-)(?=\S)/g, '')

3 Comments

this only replace string
that's not true, it also replaces specials chars, try the following: "$-$".replace(/(?=\S)(-)(?=\S)/g, '')
You probably meant to use /(?<=\S)-(?=\S)/g. However, the lookbehind is not yet supported in all browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.