Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  24] [ 7]  / answers: 1 / hits: 24255  / 8 Years ago, sun, april 3, 2016, 12:00:00

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.


More From » regex

 Answers
18

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 '));




[#62711] Thursday, March 31, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gideons

Total Points: 197
Total Questions: 106
Total Answers: 108

Location: Moldova
Member since Sat, Jan 29, 2022
2 Years ago
;