【问题标题】:How to remove \r\n from string at :如何从字符串中删除 \r\n :
【发布时间】:2021-07-12 02:20:25
【问题描述】:

嘿,我试图拆分从文件中读取的一行,该文件包含几行类似的行

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

等等,我不知道如何同时执行它们并将它们分成 2 个不同的变量,一个用于用户名,一个用于密码。

【问题讨论】:

  • .split(":") ?
  • 我试过了,也试过了 .toString 所以我可以在 \r\n 处重新分割,然后它只会在 : 处添加一个逗号
  • 你试过什么?显示您的代码。
  • 密码以明文形式存储在文件中?作为原则,我现在应该停止提供帮助吗?

标签: javascript node.js split


【解决方案1】:

使用正则表达式和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);

【讨论】:

    【解决方案2】:

    请尝试以下代码。

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

    【讨论】:

      【解决方案3】:

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

      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)

      【讨论】:

        【解决方案4】:

        使用 .replace 方法

        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'},...];
        

        【讨论】:

          猜你喜欢
          • 2021-12-06
          • 2016-06-20
          • 2022-01-24
          • 2011-05-10
          • 2016-01-05
          • 2019-02-04
          • 2019-10-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多