-1

How do I extract certain parts of a string from a whole string?

My string looks like:

&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password  

I want to extract the username and password values into 2 variables.

These values can appear in any order in the string.

user1063287
  • 10,265
  • 25
  • 122
  • 218

3 Answers3

0

It can be done this way:

let a  = '&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password'.split('&')
let user, passwordData
for(let i=0; i<a.length; i++){
  if (a[i].includes('username=')){
    user= a[i].substr(9)
  }
  if (a[i].includes('password=')){
    passwordData= a[i].substr(9)
  }
}

console.log(user, passwordData) // logs values
Noob
  • 2,247
  • 4
  • 20
  • 31
  • Just tried with the snippet provided am getting undefined in my logs. Does the same code fit into IBM Gateway script? – Avinash Athreya Aug 22 '19 at 00:07
  • @AvinashAthreya no, i provided you an example of how to parse your string and get values based on requirements stated above. – Noob Aug 22 '19 at 00:23
0

Use RegEx to split your string and get value like below.

let str = '&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password';

function getResult() {
  let arr = {};
  let KeyValueResult = str.replace(/[&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
    arr[key] = value;
  });
  return arr;
}
let username = getResult()["username"];
let password = getResult()["password"];
let client_id = getResult()["client_id"];
let client_secret = getResult()["client_secret"];
let grant_type = getResult()["grant_type"];

console.log('username: ' + username + ' password: ' + password + ' client_id:  ' + client_id + ' client_secret: ' + client_secret + ' grant_type: ' + grant_type);

Function doesn't care about order. Just call with key it's give desire value.

4b0
  • 21,981
  • 30
  • 95
  • 142
0

Well, it actaully easier than that as DataPower ships the QueryString Module out-of-the-box...

const querystring = require ('querystring');
const qs = querystring.stringify('username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password');
// returns {username: 'user' , password: 'pass', ... }
console.log('username: ' + qs.username + ' password: ' + qs.password);

Read the full documentation here: https://www.ibm.com/support/knowledgecenter/SS9H2Y_7.5.0/com.ibm.dp.doc/querystring_js.html

Anders
  • 3,198
  • 1
  • 20
  • 43