0

I'm a beginner in node.js so please do excuse me if my question is foolish. As we know we can use

var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
regex.test(str);

to check whether a string contains special charecters or not .But what I'm asking is how to check for only a particular charecter means how can I check only presence of #.

I tried to do var regex = /[#]/g; regex.test(str). Although it's not working but are there any other method of doing this?

Srinivas Nahak
  • 1,846
  • 4
  • 20
  • 45

3 Answers3

5

You don't need a regex to find a single character in a string. You can use indexOf, like this:

var hasHashtag = str.indexOf('#') >= 0;

This returns true if the character is in the string.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
4

Use includes to check the existence of # in your string. You don't actually require regex to do that.

var str = 'someSt#ring';
var res = str.includes('#');
console.log(res);

str = 'someSt#ri#ng';
res = str.includes('#');
console.log(res);

str = 'someString';
res = str.includes('#');
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
2

Use indexOf

str.indexOf('#') >= 0;
phuzi
  • 12,078
  • 3
  • 26
  • 50