sumanth
sumanth

Reputation: 781

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)

Upvotes: 0

Views: 170

Answers (3)

lukkea
lukkea

Reputation: 3614

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);

Upvotes: 1

sao
sao

Reputation: 1821

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('');

Upvotes: 0

Deryck
Deryck

Reputation: 7668

Try this out - replace only 5 or more -

longStr.replace(/-{5,}/g, '')

Upvotes: 2

Related Questions