Home > Blockchain >  typescript equivalent for python stripping of non whitespace characters
typescript equivalent for python stripping of non whitespace characters

Time:02-01

  • I know I can use .trim() for removing trailing whitespace
  • Is there any way to trim non whitespace characters?
In [1]: s = 'abc/def/ghi/'
In [2]: s.strip('/')
Out[2]: 'abc/def/ghi'

I mean the equivalent of Python's strip, which doesn't work for me:

Type ".help" for more information.
> const s = "/abc/def/pop/"
undefined
> s.trim('/')
'/abc/def/pop/' # <--- last '/' was not removed

CodePudding user response:

You can use the String.replace method

function trimDashes(str){
  return str.replace(/^\/*|\/*$/g, '');
}

^ - start of the string

/* matches a slash zero or more times

| - or

/* - matches a slash zero or more times

$ - end of the string

Test it out: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABFATjAtgEQIYGcAWAprgBS6oBc5aYA5gJQDeAUIioVCCktQHTsAHADbYIhEgHoAegB0JAKgA c QBIJtADSIA5DvoBuZgF9mzCAnKJqiALy7sAIwgSAJoWAb8MCTrMWwXDghQl4hOFoSVAwcAmIyVHp6IA

  • Related