最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex to match response as 200 OK - Stack Overflow

programmeradmin1浏览0评论

For a REST call I am getting response back. I am getting response as:

call_name response_code OK

Now I want to give an if condition if my response code is either 200 or 201. So what is the regex pattern that I should use?

Example:

response.body = getOtp 200 OK

if(response.body.match()) {
    console.log("hello");
}

For a REST call I am getting response back. I am getting response as:

call_name response_code OK

Now I want to give an if condition if my response code is either 200 or 201. So what is the regex pattern that I should use?

Example:

response.body = getOtp 200 OK

if(response.body.match()) {
    console.log("hello");
}
Share Improve this question edited Feb 23, 2017 at 20:08 talemyn 7,9804 gold badges33 silver badges52 bronze badges asked Feb 23, 2017 at 19:25 user7350714user7350714 3652 gold badges6 silver badges23 bronze badges 2
  • should it be if {} else {} condition for 200 and 201 code? – RomanPerekhrest Commented Feb 23, 2017 at 19:33
  • 1 How are you making your request. You should be able to access the status code directly without using regex. see stackoverflow./questions/5344145/… and developer.mozilla/en-US/docs/Web/API/XMLHttpRequest/status – Theo Commented Feb 23, 2017 at 20:04
Add a ment  | 

4 Answers 4

Reset to default 4

You can use character set to match either 200 or 201 codes:

var response = {body:"getOtp 200 OK"};

if(response.body.match(/20[01] OK/)){
    console.log("Matching");
}

if(response.body.match(/20[01]/) && reponse.body.match(/\bOK\b/)){
    console.log("hello");
}

Hope it helps. Didn't get to test it, but It should work just fine.

if(response.body.match(/200|201/){
    console.log("hello");
}

I had the same question as OP. However I ran into a problem:

"___.match is not a function"

Thought I'd share what solved it for me:


if (String(response.status).match(/20[01]/)) {
    // do stuff
}

发布评论

评论列表(0)

  1. 暂无评论