-2

I am getting some value in JSON response. These some time contains hyphen '-'. So in javascript '-' hyphen treated as a subtraction.

JSON

books": {
"red": "2008-17801",
"blue": "TERTERIAN-HAYK"
}

After getting these values I am putting into the array.

LIKE

["2008-17801"]
["TERTERIAN-HAYK"]

But before the assigning I want to check value has hyphen'-' or not. I checked one link, But it is checking all special characters. jQuery: Check if special characters exists in string.

I want to check only hyphen.

Varun Sharma
  • 4,632
  • 13
  • 49
  • 103
  • you get a string, you want a string, what is the problem? – Nina Scholz Feb 08 '18 at 09:10
  • 1
    `These some time contains hyphen '-'. So in javascript '-' hyphen treated as a subtraction.` that's true, but the hyphen is in a string in your case, so I don't see how that's an issue you need to worry about. Could you please edit the question to include the code which has this problem – Rory McCrossan Feb 08 '18 at 09:12
  • what issue you are getting because of `-` there? i am unable to see any issue – Alive to die - Anant Feb 08 '18 at 09:13
  • 2
    You can use `indexOf` - `str.indexOf("-") != -1` – gurvinder372 Feb 08 '18 at 09:13
  • You can pass a regex to `match()`. See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match – JJJ Feb 08 '18 at 09:13

3 Answers3

1

You can simply check the index of the - hyphen in the value of the books key.

var data = {
  "books": {
  "red": "2008-17801",
  "blue": "TERTERIAN-HAYK"
  }
};

for(var book in data.books){
  if(data.books[book].indexOf('-') !== -1){
    console.log("There is hyphen in book "+book);
  }
}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You can use replace() to find if the value contains '-' and replace it with ' ' or anything else you would like before storing it in the array.

books["blue"].replace(/-/,' ');

or if you just want to find if '-' exists then you can use match() with regex.

Abhishek Jain
  • 826
  • 8
  • 20
0

For getting all values?

var books = {
   "red": "2008-17801",
   "blue": "TERTERIAN-HAYK"
};
var allValues = Object.values( books );

For checking if there is a hyphen in any values?

var hasHypen = allValues.some ( s => s.indexOf( "-" ) != -1 );

Getting only those values which have hyphen?

var hyphenValues = allValues.filter( s => s.indexOf( "-" ) != -1 );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94