Javascript 使用IBM网关脚本返回字符串的选定部分

Javascript 使用IBM网关脚本返回字符串的选定部分,javascript,api,ibm-datapower,Javascript,Api,Ibm Datapower,如何从整个字符串中提取字符串的某些部分 我的字符串看起来像: &username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password 我想将用户名和密码值提取到两个变量中 这些值可以在字符串中以任意顺序出现 可以这样做: let a = '&username=user&password=pass&client_id=cid&

如何从整个字符串中提取字符串的某些部分

我的字符串看起来像:

&username=user&password=pass&client_id=cid&client_secret=secret&grant_type=password  
我想将
用户名
密码
值提取到两个变量中


这些值可以在字符串中以任意顺序出现

可以这样做:

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
let a='&username=user&password=pass&client\u id=cid&client\u secret=secret&grant\u type=password'.split('&'))
让用户输入密码数据

对于(让i=0;i使用RegEx分割字符串并获得如下值)。
let str='&username=user&password=pass&client\u id=cid&client\u secret=secret&grant\u type=password';
函数getResult(){
设arr={};
让KeyValueResult=str.replace(/[&]+([^=&]+)=([^&]*)/gi,函数(m,键,值){
arr[键]=值;
});
返回arr;
}
让username=getResult()[“username”];
让password=getResult()[“password”];
让client_id=getResult()[“client_id”];
让client_secret=getResult()[“client_secret”];
让grant_type=getResult()[“grant_type”];

console.log('username:'+username+'password:'+password+'client\u id:'+client\u id+'client\u secret:'+client\u secret+'grant\u type:'+grant\u type);
事实上,这比这要容易得多,因为DataPower将查询字符串模块开箱即用

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);

阅读此处的完整文档:

刚刚尝试使用提供的代码片段,我的日志中没有定义。相同的代码是否适合IBM网关脚本?@AvinashAthreya没有,我提供了一个示例,说明如何根据上述要求解析字符串并获取值。您的意思是
const qs=querystring.parse('usern…