Home > database >  Reverse a string except for the characters contained within { } with javascript
Reverse a string except for the characters contained within { } with javascript

Time:10-12

I need to reverse a string except the characters inside of "{}". I know how to reverse a string but I'm not sure how to create the exception. Please help.

 function reverseChar(string2){
    let string2Array = string2.split('');
    let newArray = [];
  
    for(let x = string2Array.length-1; x >= 0; x--){
      newArray.push(string2Array[x])
    }
    console.log(newArray)

}
reverseChar("ab{cd}efg")
reverseChar("ab{cd}ef{gh}i")

CodePudding user response:

Or, maybe, this is what you want?

function reverse(str) {
  return str.split("").reverse().join("").replace(/}\w \{/g,a=>reverse(a))
}

console.log(reverse("ab{cd}efg"))
console.log(reverse("ab{cd}ef{gh}i"))

CodePudding user response:

You can try this logic:

  • Get all the parts
  • If the part does not have special character, reverse it and set it.
  • Reverse the parts array
  • Join all the parts back and return it

function reverseChar(string2) {
  const regex = /(\w (?=\{|$)|\{\w \})/g
  return string2.match(regex)
    .map((str) => /\{/.test(str) ? str : str.split("").reverse().join(""))
    .reverse()
    .join("")
}
console.log(reverseChar("ab{cd}efg"))
console.log(reverseChar("ab{cd}ef{gh}i"))

  • Related