Muta șirul care se potrivește cu regex la capăt

Discutii si intrebari legate de scripturi si functii JavaScript, jQuery si Ajax, cod JavaScript in general.
Marius
Mesaje: 60

Muta șirul care se potrivește cu regex la capăt

Am următoarea problemă de rezolvat în JavaScript:
- Găsiți textul care se află între paranteze mici și deplasați textul cu parantezele la capătul sirului, utilizând regex.

Să spunem că am acest șir:

Cod: Selectaţi tot

let str ='Have a (good) life';
Trebuie sa rezulte:

Cod: Selectaţi tot

let str ='Have a life (good)';

MarPlo Mesaje: 4343
Incearca urmatorul cod:

Cod: Selectaţi tot

function testToEnd(str){
  //get matched string
  let st = str.match(/[ ]*\([^\)]+\)[ ]*/g)
  if(st){
    st = st[0];

    // replace the matched string and append it to end
    str = str.replace(st, ' ')+st;
  }
  return str;
}

let str1 ='Have a (good) life';
let str2 ='Forgiveness heals the mind.';

console.log(testToEnd(str1));  // Have a life (good)
console.log(testToEnd(str2));  // Forgiveness heals the mind.

Subiecte similare