skip to Main Content

I have string which can end either with " *" or " **" or just without space and star.
I have to trim of any space or stars at the end of the string, but I can’t get it to work

trimStarsOff(strWithStars: string): string {
    const returnStr = strWithStars;
    if (strWithStars.includes('*')) {
      const test = strWithStars.replace(' \*$', '');
      cy.log(`test ${test}`);
    }
    return returnStr;
}

The stars remain in my case:

test "Some words test *"

test "Other words test2 *"

What do I miss?

3

Answers


  1. First, use a regular expression literal instead of a string. Also, use + to allow one or more asterisks to be replaced.

    const trimStarsOff = s => s.replace(/ *+$/, '');
    console.log(trimStarsOff('Some words test *'));
    console.log(trimStarsOff('Test ***'));
    Login or Signup to reply.
  2. You’re trying to use a regex in a string instead of just using the /regex/ format (technically you could also use the RegExp constructor with a string). You also don’t need to check if you need to replace, just attempt a replacement and if you get the input echoed as the output, that’s fine.

    function trimStarsOff(strWithStars) {
        return strWithStars.replace(/ *+$/, '');
    }
    
    console.log(trimStarsOff("foo bar"));
    console.log(trimStarsOff("banana sandwich *"));
    console.log(trimStarsOff("corn on the cob **"));
    console.log(trimStarsOff("stack overflow"));
    Login or Signup to reply.
  3. If you want to have it universal with any number of spaces and stars:

    const log = str => console.log(JSON.stringify(str));
    
    function trimStarsOff(strWithStars) {
        return strWithStars.replace(/[*s]+$/, '');
    }
    
    log(trimStarsOff("foo bar"));
    log(trimStarsOff("banana sandwich *"));
    log(trimStarsOff("corn on the cob * *"));
    log(trimStarsOff("stack overflow  *** *"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search