如何从以下位置的字符串中删除\r\n:

up9lanfz  于 2021-09-13  发布在  Java
关注(0)|答案(4)|浏览(321)

嘿,我正在尝试拆分从文件中读取的一行,该文件包含几个读起来像

username:password\r\n
username:password\r\n
username:password\r\n

等等,我不知道如何在同一时间完成它们,并将它们分成两个不同的变量,一个是用户名,一个是密码。

d8tt03nd

d8tt03nd1#

使用正则表达式和 matchAll() ,并将返回的迭代器传递给 Array.from() 以及使用内置的 map() 返回对象(有允许的额外好处吗 : (输入密码)

const input = 'user1:password1\r\nuser2:password2\r\nuser3:password3\r\n';

const result = Array.from(
  input.matchAll(/(.+?):(.+?)\r\n/g),
  ([, username, password]) => ({ username, password })
);

console.log(result);
rqmkfv5c

rqmkfv5c2#

请尝试下面的代码。

var mainStr = "username:password\r\nusername:password\r\nusername:password\r\n";

var usernameArr = [];
var passwordArr = [];
mainStr.split("\r\n").forEach(str => {
  var strArr = str.split(":");
  strArr[0] && usernameArr.push(strArr[0]);
  strArr[1] && passwordArr.push(strArr[1]);
});
console.log("Username ", usernameArr);
console.log("Password ", passwordArr);
6ioyuze2

6ioyuze23#

您可以将其转换为键/值对数组

let lines = `john:123443\r\n
alan:ffg1234\r\n
someone:xxghj!34\r\n`;

let pairs = lines.split("\r\n") // convert into an array
    .map(l => l.split(':') // split on the :
    .map(e => e.replaceAll("\r", "").replaceAll("\n", ""))) // clear out any extra newlines that lingered
    .filter(e => e.join('').trim() != '') // filter out any empties gathered along the way
    .map(grp => ({username: grp[0], password: grp[1]})) // transform the array into key/value pairs

console.log(pairs)
mmvthczy

mmvthczy4#

使用。替换方法

const str ='username:password\r\n'
const username = str.split(:)[0];
const password = str.split(:)[1].replace(/[\r\n]+/g, '');

对于完整字符串:

const str =`username:password\r\n
username:password\r\n
username:password\r\n`;

const res = str.split(/[\r\n]/g)
               .filter(l=>l!=="")
               .map(s=>({username:s.split(':')[0], password:s.split(':')[1]}));

console.log(res)
// [{username:'username', password:'password'},...];

相关问题