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.
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 May I ask what does “i” do? Your code also works without “i”.
$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,
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.