【问题标题】:How to expand and collapse an array of single-characters?如何展开和折叠单字符数组?
【发布时间】:2019-12-29 15:30:57
【问题描述】:

我正在处理由于某种原因已变异为单字符数组的数据(长字符串)。这是一个例子:

['f', 'o', 'o', ' ', 't', 'e', 's','t', ' ', 'b', 'a', 'r']

我需要执行一些正则表达式,将其作为普通字符串进行搜索/替换。所以我需要把它转换成普通的

'foo test bar'

...对此进行一些突变,例如将“test”替换为“hi”,然后将其返回到以前的状态:

['f', 'o', 'o', ' ', 'h', 'i' ' ', 'b', 'a', 'r']

我想我来自 C++ 背景,我想将这个 char 字符串视为 char* 而无需进行一些昂贵的操作。

【问题讨论】:

    标签: javascript arrays string collapse expand


    【解决方案1】:

    您可以join 将数组转换为字符串。 replace这个词test。并使用Array.from()将其转换回字符数组

    const array = ['f', 'o', 'o', ' ', 't', 'e', 's', 't', ' ', 'b', 'a', 'r'],
          output = Array.from(array.join('').replace('test', 'hi'));
    
    console.log(output)

    【讨论】:

      【解决方案2】:

      您可以使用.join()将数组转换为字符串,例如:

      let  str =['f', 'o', 'o', ' ', 't', 'e', 's','t', ' ', 'b', 'a', 'r'].join(" "));
      
      //return 'foo test bar'
      

      然后你用.replace替换String,例如:

      str.replace('test','hi');
      

      您也可以使用 .split("") 将字符串转换为数组,例如:

      console.log('foo test bar'..split(""));
      
      //return ['f', 'o', 'o', ' ', 'h', 'i' ' ', 'b', 'a', 'r']
      

      【讨论】:

        猜你喜欢
        • 2014-10-08
        • 1970-01-01
        • 2018-12-13
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-16
        • 2016-12-23
        相关资源
        最近更新 更多