0

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)
sumanth
  • 751
  • 2
  • 15
  • 34

3 Answers3

2

Try this out - replace only 5 or more -

longStr.replace(/-{5,}/g, '')
Deryck
  • 7,608
  • 2
  • 24
  • 43
1

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);
lukkea
  • 3,606
  • 2
  • 37
  • 51
0

use split to split the string into an array, then use pop however many times to remove characters at the end. you can test the last character each time and use pop if its a "-"

//js
const longStr = "Hello ---- TecAdmin------------";
let splitLongStr = longStr.split('');

for (let i=0; i<splitLongStr.length; i++) {
  splitLongStr.pop();
}

let longStrChopped = splitLongStr.join('');
sao
  • 1,835
  • 6
  • 21
  • 40
  • this works, i just tested in a node JS env. it might leave you with one left over dash, just modify how many times you run the loop `i<...` and have fun! problem solved – sao Sep 21 '19 at 14:37