Search code examples
javascriptnode.jsstringtrim

How to trim an unwanted continuous string at end in javascript?


I am trying to trim a string with unnecessary characters at the end as below. I would appreciate either if someone corrects me or provide me an easy approach!!

Expected Result: finalString, Hello ---- TecAdmin

const longStr = "Hello ---- TecAdmin------------";

function trimString(str) {
  const lastChar = str[str.length - 1];
  if(lastChar === '-') {
   str = str.slice(0, -1);
   trimString(str);
  } else {
   console.log(str,'finally')
   return str;
  }
}

const finalString = trimString(longStr);

console.log('finalString', finalString)


Solution

  • Working off Deryck's comments & answer, but allowing for any number of dashes on the end:

    const longStr = "Hello ---- TecAdmin------------";
    var thing = longStr.replace(/-*$/g, '');
    console.log(thing);