Posted By

ira on 04/20/09


javascript RegularExpression

Versions (?)

Replace Spaces with Underscores

 / Published in: JavaScript

  1. var str = "This string has too many spaces.";
  2. var result = str.replace(/\s/gi, "_");
  3. document.write(result);

Report this snippet  


RSS Icon Subscribe to comments
Posted By: duniyadnd on April 21, 2009

You're missing out a couple of items: because you're using Javascript, keep in mind of   ( you can also look at   - I think). Your script also treats multiple spaces/tabs/white spaces as it's own entity, which could lead to undesired results. An alternative is:

var result = str.replace(/(\s| | )+/gi, "_");

Posted By: duniyadnd on April 21, 2009

Ugh, don't know why it didn't show up properly - I've put the code here:

You need to login to post a comment.