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.
JavaScript
x
12
12
1
function reverseChar(string2){
2
let string2Array = string2.split('');
3
let newArray = [];
4
5
for(let x = string2Array.length-1; x >= 0; x--){
6
newArray.push(string2Array[x])
7
}
8
console.log(newArray)
9
10
}
11
reverseChar("ab{cd}efg")
12
reverseChar("ab{cd}ef{gh}i")
Advertisement
Answer
Or, maybe, this is what you want?
JavaScript
1
6
1
function reverse(str) {
2
return str.split("").reverse().join("").replace(/}w+{/g,a=>reverse(a))
3
}
4
5
console.log(reverse("ab{cd}efg"))
6
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.