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

How to add a special character while using join() in javascript?

I am developing a project with angular, and I have come across a problem while joining an array to a string and splitting it with ‘,’

Here’s an example

let numbers = [2019, 2020, 2021, 2022, 2023] numbers.toString().split(',').join(', ')

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

Outputs as

"2019, 2020, 2021, 2022, 2023"

Here’s my problem I want an & symbol at the 2nd last of last number being parsed

Output something like

"2019, 2020, 2021, 2022 & 2023"

Is there any elegant way to do with while doing split().join()

I know of brute force ways (there are many), but any optimal way of doing this?
Thanks in advance.

I tried doing pushing at index(-2) from the end, not an elegant way tbh, the numbers array is very dynamic.

splitting the string and then looping over it and at the end when we encounter the last space, replacing it with &, but this will require creating a copy of whole string.

>Solution :

We can use Array.slice() and Array.at() to do it

let numbers = [2019, 2020, 2021, 2022, 2023]  
let result = numbers.slice(0,-1).toString().split(',').join(', ')+ ' & ' + numbers.at(-1)
console.log(result)
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