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")
Advertisement
Answer
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"))
The RegExp /}w+{/g
will find any string of characters and numbers (w+
) that is enclosed by }
and {
. These patterns will exist after the whole string is reverse()
-d initially. In the callback function to the String.replace()
method the matched string will then be reversed again.