Reputation: 2834
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
Reputation: 42109
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);
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
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