How to remove specific character surrounding a string?
Search for character mask and return the rest without.
This proposal the use of the bitwise not ~
operator for checking.
~
is a bitwise not operator. It is perfect for use withindexOf()
, becauseindexOf
returns if found the index0 ... n
and if not-1
:
value ~value boolean -1 => 0 => false 0 => -1 => true 1 => -2 => true 2 => -3 => true and so on
function trim(s, mask) { while (~mask.indexOf(s[0])) { s = s.slice(1); } while (~mask.indexOf(s[s.length - 1])) { s = s.slice(0, -1); } return s;}console.log(trim('??? this is a ? test ?', '? '));console.log(trim('abc this is a ? test abc', 'cba '));
Simply use:
let text = '?? something ? really ??'text = text.replace(/^([?]*)/g, '')text = text.replace(/([?]*)$/g, '')console.log(text)
A possible solution would be to use recursive functions to remove the unwanted leading and trailing characters. This doesn't use regular expressions.
function ltrim(char, str) { if (str.slice(0, char.length) === char) { return ltrim(char, str.slice(char.length)); } else { return str; }}function rtrim(char, str) { if (str.slice(str.length - char.length) === char) { return rtrim(char, str.slice(0, 0 - char.length)); } else { return str; }}
Of course this is only one of many possible solutions. The function trim
would use both ltrim
and rtrim
.
The reason that char
is the first argument and the string that needs to be cleaned the second, is to make it easier to change this into a functional programming style function, like so (ES 2015):
function ltrim(char) { (str) => { <body of function> }}// No need to specify str herefunction ltrimSpaces = ltrim(' ');