-5

I am trying to evaluate if a string is equal to one of these symbols |\~+

But this doesn't work:

var a = 'abcted',
    b = '|\~+';

if( a !== b ){
}

So if a is equal to one of the symbols in b, is evaluates to false.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
gespinha
  • 7,968
  • 16
  • 57
  • 91
  • 2
    Are you doing a string to string comparison, or are you trying to see if any one singular character in b is in the string a? – vandsh Jun 08 '15 at 18:56
  • possible duplicate of [How can I check if one string contains another substring?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring) –  Jun 08 '15 at 19:05
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – thefourtheye Jun 08 '15 at 19:07

3 Answers3

4

You can simply check if one string contains another using the method indexOf:

var b = '|\~+';
if (b.indexOf(a) == -1) {
  // b doesn't contain a
}

A new suggestion is made for the function includes, which would work like this, but not (yet) in many browsers.

var b = '|\~+';
if (!b.includes(a)) {
  // b doesn't contain a
}
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
3

You can use Regular Expression to solve this, like this

if (/[|\\~\+]/.test(a) === false) {
    // `a` doesn't contain any of the symbols.
}

[|\\~\+] checks if any of the characters in the character group is in a. If none of them are there then test will return false.

console.log(/[|\\~\+]/.test("abcted"));
// false
console.log(/[|\\~\+]/.test("abc|ted"));
// true
console.log(/[|\\~\+]/.test("abc\\ted"));
// true
console.log(/[|\\~\+]/.test("abc~ted"));
// true
console.log(/[|\\~\+]/.test("abc+ted"));
// true
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

I prefer to use RegEx where possible, but for those who are not wanting to:

var a = 'abcted',
    b = '|\~+';

for (var i = 0, len = b.length; i < len; i++) {
    if (a.indexOf(b[i]))  
    {   
        alert(b[i]);
    }
}
vandsh
  • 1,329
  • 15
  • 12