-5

How would I remove _100 from the end of the string, It should be removed only at the end of the string. For e.g marks_old_100 should be "marks_old". marks_100 should be "marks".

function numInString(strs) {
  let newStr = ''
  for (let i = 0; i < strs.length; i++) {
    let noNumRegex = /\d/
    let isAlphRegex = /[a-zA-Z]$/
    if (isAlphRegex.test(strs[i])) {
      newStr += strs[i]
    }
  }
  return newStr
}

console.log(numInString('marks_100'))
adiga
  • 34,372
  • 9
  • 61
  • 83

2 Answers2

0

Try:

string.replace(/_\d+$/g, "")

It makes use of regexes, and the $ matches the end of the string. .replace then replaces it with an empty string, returning the string without \d+ on the end. \d matches any digits, and + means to match more one or more.

Alternatively, if you want to match the end of a word, try:

string.replace(/_\d+\b/g, "")

which utilises \b, to match the end of a word.

Geza Kerecsenyi
  • 1,127
  • 10
  • 27
0

Please check the following snippet:

const s = 'marks_old_100';

// remove any number
console.log(s.replace(/_[0-9]+$/, ''));

// remove three digit number
console.log(s.replace(/_[0-9]{3}$/, ''));

// remove _100, _150, _num
console.log(s.replace(/_(100|150|num)$/, ''));
Long Nguyen Duc
  • 1,317
  • 1
  • 8
  • 13