Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace in a string different characters with other characters

Suppose the string One two (three)

In PHP, in order to replace the spaces with a dash, and parentheses with an empty string, I’d do it like this: str_replace( array( ' ', '(', ')' ), array( '-' ), $key ), because search arg is an array, replace is an array also, and replace has fewer elements than search, so the remaining elements from search are replaced with an empty string…

I’m not very good in JS, so I needed to achieve something similar, like turning One two (three) to One-two-three, and tried with chained replace commands. But it doesn’t work in the expected way. Obviously I’m doing something wrong, but what is it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var text="one two (three)";

alert(text.replace("(", "").replace(")", "").replace(" ", "-"));

>Solution :

replace will only replace the first occurence. Use replaceAll instead of replace to replace all occurrences.

var text="one two (three)";

alert(text.replaceAll("(", "").replaceAll(")", "").replaceAll(" ", "-"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading