Shift N' Tab Shift N' Tab - 2 months ago 12
Javascript Question

How to replace specific char in a string javascripts

I would like to remove the given char if it occurred more than once.



var input = "12313*12313*13";
var count = (input.match(/[*]/g) || []).length;

if (count > 1)
{
x = 0;
for (var i = 0, len = input.length; i < len; i++) {
if (input[i] == '*')
{
if (x == 0)
{
x++;
continue;
}
input[i] = '';
}
}
}

console.log(input);





The given char is
*
and i would like to remove the other
*
from the string.

I would like to have this output
12313*1231313
.

Answer

A simpler solution using lastIndexOf and substring:

This solution just works whit 2 occurrences:

var input = "12313*12313*13";
var count = (input.match(/[*]/g) || []).length;

if (count > 1) {
  var i = input.lastIndexOf('*');
  input = input.substring(0, i) + input.substring(i + 1);
}

console.log(input);

This is refactor of the previous one which works whit N occurrences:

var input = "12313*12313*13*12*13232*12312";
var count = (input.match(/[*]/g) || []).length;
var i;

while(count > 1) {
  i = input.lastIndexOf('*');
  input = input.substring(0, i) + input.substring(i + 1);
  count--;
}

console.log(input);