Javascript Character Replacement

So you need to replace all the occurrences of a character in a javascript variable… Well that’s not too hard.

I’ll put the code into a function that you can call from anywhere in javascript.

I decided to use a regular expression in the replace syntax… No real reason though. But it works. The idea here is that you call the function, the string you want to check is passed through the regular expression and all the commas are replaced by an “_” (or any other character you choose).

<script type="text/javascript">
  function removeComma(field) {
    field = field.replace(/,/g,"_");
    return field;
  }
</script>

removeComma('this is the, string, I want to check, for commas');

Result: “this is the_ string_ I want to check_ for commas”.


Leave a Reply