title: JavaScript replace string and comma if comma exists else only the string
body: <p>I got a string like:</p>
  
  <pre><code>var string = "string1,string2,string3,string4";
  </code></pre>
  
  <p>I got to replace a given value from the string. So the string for example becomes like this:</p>
  
  <pre><code>var replaced = "string1,string3,string4"; // `string2,` is replaced from the string
  </code></pre>
  
  <p>Ive tried to do it like this:</p>
  
  <pre><code>var valueToReplace = "string2";
  var replace = string.replace(',' + string2 + ',', ''); 
  </code></pre>
  
  <p>But then the output is:</p>
  
  <pre><code>string1string3,string4
  </code></pre>
  
  <p>Or if i have to replace <code>string4</code> then the <code>replace</code> function doesn't replace anything, because the comma doens't exist.</p>
  
  <p>How can i replace the value and the commas <strong>if the comma(s) exists</strong>?
  If the comma doesn't exists, then only replace the <code>string</code>.</p>