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
First, use a regular expression literal instead of a string. Also, use
+
to allow one or more asterisks to be replaced.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.
If you want to have it universal with any number of spaces and stars: