[SOLVED] How to remove specific character surrounding a string?


I have this string:

var str = "? this is a ? test ?";

Now I want to get this:

var newstr = "this is a ? test";

As you see I want to remove just those ? surrounding (in the beginning and end) that string (not in the middle of string). How can do that using JavaScript?

Here is what I have tried:

var str = "? this is a ? test ?";
var result = str.trim("?");

So, as you see it doesn’t work. Actually I’m a PHP developer and trim() works well in PHP. Now I want to know if I can use trim() to do that in JS.

It should be noted I can do that using regex, but to be honest I hate regex for this kind of jobs. Anyway is there any better solution?

Edit: As this mentioned in the comment, I need to remove both ? and whitespaces which are around the 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 with indexOf(), because indexOf returns if found the index 0 ... 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 '));

Answered By – Nina Scholz

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *