Move the string that matches the regex to the end

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

Move the string that matches the regex to the end

I have the following problem to solve it in JavaScript:
- Find the text which is between small brackets and shift that text with the brackets to the end of the string, using regex.

Let say I have this string:

Code: Select all

let str ='Have a (good) life';
It must result:

Code: Select all

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

MarPlo Posts:186
Try the following code:

Code: Select all

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.