skip to Main Content

I currently have a string as follows:

[accept,#PID<0.395.0>,{id:N1,num:1},Appeltaart]

To improve readability I would like to add spaces behind the , and : characters. I know I can do this using the replaceAll() function twice, as follows:

someString.replaceAll(':', ': ').replaceAll(',', ', ')

But this doesn’t seem efficient, especially if next time I wanted to add spaces behind 5 characters. Is there a more efficient approach to tackle this problem?

2

Answers


  1. use regex for that, to add more characters to the list add them to the re variable:

    let str = '[accept,#PID<0.395.0>,{id:N1,num:1},Appeltaart]'
    
    let re = /(,|:)/g
    
    let result = str.replace(re,"$1 ")
    
    console.log(result)
    Login or Signup to reply.
  2. If i understand what you want, try this code and see if it work for you

    let text = "[accept,#PID<0.395.0>,{id:N1,num:1},Appeltaart]";
    let result = (text.replace(/,/g, ', ')).replace(/:/g, ': ');
    console.log(result); // output [accept, #PID<0.395.0>, {id: N1, num: 1}, Appeltaart]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search