0

Hello I have a string could be like this

var str = "127"; 

or

var str ="127,5,28,12";

I want to check if number exist I don't want to add it again. So I use

if(!str.includes(id))
     // do so and so 

But the problem with includes is that If I search for 1 it will get it from 127 and that's not accurate. Is there a better way to detect exact number in js?

palAlaa
  • 9,500
  • 33
  • 107
  • 166
  • 1
    If your string always holds a comma separated value, you're better off putting those values in an array. – Ja͢ck Jun 10 '15 at 05:34
  • @Ja͢ck—"*better off*" how? The string *indexOf* method is more widely supported than the array version, so not by that criterion at least. – RobG Jun 10 '15 at 05:39
  • @RobG in the sense that perhaps a string is simply the wrong datatype. – Ja͢ck Jun 10 '15 at 05:40
  • Ok, I don't know where the OP got the *includes* method from, it seems to be being used as a method of *String.prototype*. – RobG Jun 10 '15 at 05:43

3 Answers3

3

Try:

var str ="127,5,28,12";
var exists = str.split(/,/).indexOf("127")

if(exists > -1){
    alert("127 Exists!")
}

//--- Like your example ---

String.prototype.includes = function(id){
    return this.split(/,/).indexOf(id) !== -1
}

if(str.includes("28")){
    alert("28 Exists!")
}
  • 1
    Don't add a method called `includes` to `String.prototype`, as that will be added to browsers in the next version of ECMAScript (the standard version of JavaScript): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes – Qantas 94 Heavy Jun 10 '15 at 06:06
  • @Qantas94Heavy it was like his example, but I did not know about ´includes´, thanks for the info. – Walter Chapilliquen - wZVanG Jun 10 '15 at 06:11
2

you can use:

str.split(',').indexOf('127');
Yangguang
  • 1,785
  • 9
  • 10
1

You can use word boundary (\b):

/\b127\b/.test(str)
// => true
/\b1\b/.test(str)
// => false
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    This is a more generic approach than other answers and does not require the string to be converted to a different data format. – RobG Jun 10 '15 at 05:45