[Solved] Underscore replace in javascript


You can replace all duplicate underscores with single underscores, then replace all underscores with spaces:

while (string.indexOf('__') != -1) {
  string = string.replace('__', '_');
}
while (string.indexOf('_') != -1) {
  string = string.replace('_', ' ');
}

Another way would be to loop through the string and check for underscores and output a space for the first underscore in a group:

var result="";
var space = false;
for (var i = 0; i < string.length; i++) {
  if (string[i] == '_') {
    if (!space) {
      result += ' ';
    }
    space = true;
  } else {
    result += string[i];
    space = false;
  }
}

This would of course be simpler and much more efficient using a regular expression:

string = string.replace(/_+/g, ' ');

Note: If you expect the result to have a backslash, that won’t happen. There is no backslash in the string to start with, the character combination \_ is interpreted as a _. If you want to put a backslash in the string you would use \\ in the string literal.

0

solved Underscore replace in javascript