0

in my website, I have a slug function in JavaScript. Which will replace all the special character except @ inn the string with -. It works. but not giving the desired output. What is wrong with the code?

My function is

function to_slug(string) {
    var new_str = string.trim().replace(/[^0-9a-zA-Z@]+/i, '-').toLowerCase();
    return new_str;
}

This function works for first two space strings. that is,

sample shop will give output sample-shop

but

sample shop hfnbbf giving output as sample-shop hfnbbf

and

sample shop hfnbbf.hgdsf giving output as sample-shop hfnbbf.hgdsf

Whay this is happening? please help me.. Thanks in advance

Arun
  • 3,640
  • 7
  • 44
  • 87
  • 4
    `replace` only replaces the first occurrence, respecting the regular expression basically. You need to use the `/g` flag for it to "globally" replace all occurrences. – Sergiu Paraschiv Aug 12 '14 at 09:05
  • "_This function works for first two `space` strings._" What does this mean? All three of your examples just show the function doing nothing at all to the input. – JLRishe Aug 12 '14 at 09:06
  • @JLRishe : sorry.. I edited the question – Arun Aug 12 '14 at 09:08
  • @SergiuParaschiv I would just post that as an answer before someone else walks away with the "honor". – MarioDS Aug 12 '14 at 09:09

0 Answers0