theamateurdataanalyst
theamateurdataanalyst

Reputation: 2834

How to remove all commas before certain characters in javascript

Suppose I have a string such as

var x = "This is as,] sent,}encee:. Doo} youu: likei} i,:t."

I wanted to know if there is any way to remove all characters that come before either ],}, or :? This would result in

"This is as] sent}encee:. Doo} youu: likei} i:t."

I know I could probably loop through the string, but do you guys know what any simpler ways?

EDIT: Sorry how would you address this if you only wanted to replace the , that come before ],}, or :?

Upvotes: 0

Views: 153

Answers (2)

vol7ron
vol7ron

Reputation: 42109

Regex Replacement

Replace with a regex looking for a comma followed by your specific character, and replace them with the special character (e.g., ",:" => ":").

var x = "This is as,] sent,}encee:. Doo} youu: likei} i,:t.";
x = x.replace(/,([\]:}])/g, "$1");

alert(x);

String Replacement

You could also use the following string replacement method, chaining replacements, but it's important to note that the global replace flag ("g") won't work in v8 JS engine, like Chrome (and I think Safari), so use this method with caution:

var x = "This is as,] sent,}encee:. Doo} youu: likei} i,:t.";
x = x.replace(',]', ']', "g")
     .replace(',}', '}', "g")
     .replace(',:', ':', "g");

alert(x);

Upvotes: 1

brenjt
brenjt

Reputation: 16297

You can do it with javascripts regular expression replace:

x.replace(/,([\]\}\:])/gi, '$2')

\, will capture one character

([\]\}\:]) will capture the next character if it is a ],: or }

The gi will make it global search and case-insensitive.

var x = "This is as,] sentencee,:. Doo,} youu: likei,} it."
var y = x.replace(/,([\]\}\:])/gi, '$1');
document.write(y);

Upvotes: 2

Related Questions