Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("?");
document.write(result);

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.

like image 336
Shafizadeh Avatar asked Apr 03 '16 20:04

Shafizadeh


People also ask

How do you get rid of a certain character in a string?

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.

How do you remove all of a certain character from a string Java?

You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.

How do I remove certain letters from a string in Python?

In Python you can use the replace() and translate() methods to specify which characters you want to remove from the string and return a new modified string result. It is important to remember that the original string will not be altered because strings are immutable.


1 Answers

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 '));
like image 119
Nina Scholz Avatar answered Sep 22 '22 19:09

Nina Scholz