如何展开和折叠单字符数组?

How to expand and collapse an array of single-characters?

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

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

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

'foo test bar'

... 对此执行一些突变,例如将 "test" 替换为 "hi",然后 return 将其恢复到原来的状态:

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

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

你可以join the array to convert it to a string. replace the word test. And convert it back to an array of characters using 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)

您可以使用.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']