Page 1 of 1

Move the string that matches the regex to the end

Posted: 30 Nov 2020, 07:17
by Marius
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)';

Move the string that matches the regex to the end

Posted: 30 Nov 2020, 08:51
by MarPlo
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.