0

I have a string like below. const myString =

"{
    "typ": "JWT",
    "alg": "44555"
}
{
    "XForwardedFor": "12.134.234.22",
    "sm_AppId": "test",
    "UserId": "changu",
    "sm_Userdn": "some userdn",
    "Mail": "[email protected]",
    "DomainName": "www.test.com",
    "UserAgent": "Amazon",
    "CreationTime": "2020-09-08T05:01:55.616Z"
}
ii( NJm)'d=IXp:$uG\mf  }"

I need to get userID and Mail from the above using regex. How can I achieve it. I tried with below regex code but didnt find luck.

myString.match(/"UserId":"([\s\S]*?)"/i);
4
  • 2
    why dont you use JSON.parse? Commented Sep 9, 2020 at 5:49
  • Well, the string needs some sanitising first to make it a valid JSON string. Commented Sep 9, 2020 at 5:50
  • @cars10m yes. This is what I am getting as API response.. So I need only userID and Mail from the response. Commented Sep 9, 2020 at 5:55
  • If you really want to use regex, then "(?:UserId|Mail)"\s*:\s*"([^"]+)" might help Commented Sep 9, 2020 at 6:03

2 Answers 2

2

As the string looks like a JSON document, instead of trying to build a regexp to extract the email you should probably just parse the JSON with JSON.parse(// ....

The problem is that your string is not a valid JSON document but if the format won't change you can probably do something like that:

const myString = `{
    "typ": "JWT",
    "alg": "44555"
}
{
    "XForwardedFor": "12.134.234.22",
    "sm_AppId": "test",
    "UserId": "changu",
    "sm_Userdn": "some userdn",
    "Mail": "[email protected]",
    "DomainName": "www.test.com",
    "UserAgent": "Amazon",
    "CreationTime": "2020-09-08T05:01:55.616Z"
}
ii( NJm)'d=IXp:$uG\mf  }`
const regexp = /\{[^\}]*\}/gs
const email = JSON.stringify(myString.match(regexp)[1]).Mail

Sign up to request clarification or add additional context in comments.

Comments

0

After carving out the valid JSON portion from the string you can parse it and access the properties you need:

const resp=`{
"typ": "JWT",
"alg": "44555"
}
{
"XForwardedFor": "12.134.234.22",
"sm_AppId": "test",
"UserId": "changu",
"sm_Userdn": "some userdn",
"Mail": "[email protected]",
"DomainName": "www.test.com",
"UserAgent": "Amazon",
"CreationTime": "2020-09-08T05:01:55.616Z"
}
ii( NJm)'d=IXp:$uG\mf  }`
let obj=JSON.parse(resp.match(/\{[^{]*UserId[^}]*\}/))

console.log(obj.UserId, obj.Mail)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.