0

I have a string that looks like this :

LE PUY EN VELAY (NIVEAU_SITE)LYON 03 (@A)01AIGLETTE (GEX)

What I need is to modify this string so that each time it finds the character ) it adds a , just after.

It would look like this :

LE PUY EN VELAY (NIVEAU_SITE), LYON 03 (@A), 01AIGLETTE (GEX)

The last ")" doest not have to have a "," sign after

4 Answers 4

2

You can try with replace() and regex /\)(?=.*\))/g

Where

\) matches the character ) literally

Positive Lookahead (?=.*\))

.* matches any character (except for line terminators)

var str = "LE PUY EN VELAY (NIVEAU_SITE)LYON 03 (@A)01AIGLETTE (GEX)";
str = str.replace(/\)(?=.*\))/g,"), ");
console.log(str);

Sign up to request clarification or add additional context in comments.

1 Comment

@Mamum OP updated the question, you might want to update your answer as well :)
1

Use split join and splice

var a = "LE PUY EN VELAY (NIVEAU_SITE)LYON 03 (@A)01AIGLETTE (GEX)";
var x = a.split('');

x.forEach(function(e, j) {
  if (e == ')')
    x.splice(j + 1, 1, ',')
})

x[x.length - 1] = '';
console.log(x.join(''))

Comments

1

While Mamum answer is most optimised and clean but if you don't know regular expression, you can do something like this

You can try something like this..

  1. Split and make it into array
  2. Map the array and make changes accordingly (using if-else condition)
  3. Join the Array

 let str = "LE PUY EN VELAY (NIVEAU_SITE)LYON 03 (@A)01AIGLETTE (GEX)";

str = str.split('').map((el, index) => {
  if (str.length === index + 1) return el
  if (el === ')')  return '),'
  else return el
})
console.log(str.join(''));

Comments

1
const updateString = (str)=>{

    str = str.replace(/["')]/g,"),");
    if(str.charAt(str.length -2) == ')' && str.charAt(str.length -1) == ',' ){

                str = str.slice(0, str.length-1);
          }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.