Replace one or more of the same character in a string

Hi,

I know the basic method to remove all occurrences of a hyphen (-) :

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

I have a string that has one or more hyphens multiple times:

---this-is-my--string----that-i--want---to-change-

and I want to accomplish two things

  1. Replace all multiple hyphens with one single hyphen,
  2. Remove hyphens at the beginning and at the end.

The result should be:

this-is-my-string-that-i-want-to-change

Thanks for any ideas.

string.replace(/^-+|-+$/gi,‘’) will replace all hyphens at beginning and end of string.
string.replace(/-+/gi,‘-’) will replace one or more hyphens with a single hyphen, globally.
Using either without the global attribute will remove only the first occurrence of hyphen.

HTH,

:slight_smile:

EDIT: I should have made a little bit more research before asking. Anyway here is the solution in case someone else needs the same thing:

string.replace(/[-]+/g, '-')

If I am not wrong,

[-] : means to replace a hyphen
[-]+ : means to replace one or more hyphens (-, --, —)
/[-]+/g : means to replace multiple occurrences of one or more hyphens as in my sample string above.

Thank you, Wolf, just saw your post after posting mine :slight_smile: May I ask what does “i” do? Your code also works without “i”.

Yet another solution:



$str = "---this-is-my--string----that-i--want---to-change-";

echo $x = trim( str_replace('--', '-', $str ), '-' );

// trim removes '-' from front and back of $str


Don’t want to sound trite, but it looks like the code you suggest is PHP, but the OP asked the question in the JavaScript/jQuery forum. There is no TRIM() in JavaScript (that I am aware of.)

V/r,

:slight_smile:

UPDATE: Well, yes and no. I guess it depends upon what version of JavaScript. If the String.prototype.trim doesn’t exist, you can code for it. But it only affects whitespace, not hyphens.

Whoops, sorry about not being PHP.