gpt4 book ai didi

javascript - Node JS : extracting strings between two DIFFERENT characters and storing them in an array

转载 作者:行者123 更新时间:2023-12-02 14:12:52 25 4
gpt4 key购买 nike

使用nodejs,我需要提取两个不同字符之间的所有字符串,并将它们存储在一个数组中以供将来使用。例如,考虑一个文件,其中包含具有以下内容的文件。

"type":"multi",
"folders": [
"cities/",
"users/"
]

我需要提取单词:城市用户,并将它们放入一个数组中。一般来说,我想要“和/”之间的单词

最佳答案

Bergi在评论中提到,这看起来与 JSON ( javascript object notation 非常相似。) 所以我会假设它是这样来写我的答案。为了使当前示例成为有效的 JSON,它需要位于对象括号内,如下所示:

{
"type": "multi",
"folders": [
"cities/",
"users/"
]
}

如果你解析这个:

var parsed_json = JSON.parse( json_string );

// You could add the brackets yourself if they are missing:
var parsed_json = JSON.parse('{' + json_string + '}');

然后你需要做的就是到达数组:

var arr = parsed_json.folders;
console.log(arr);

为了修复烦人的尾部斜杠,我们重新映射数组:

// .map calls a function for every item in an array
// And whatever you choose to return becomes the new array
arr = arr.map(function(item){
// substr returns a part of a string. Here from start (0) to end minus one (the slash).
return item.substr( 0, item.length - 1 );

// Another option could be to instead just replace all the slashes:
return item.replace( '/' , '' );
}

现在尾部斜杠消失了:

console.log( arr );

关于javascript - Node JS : extracting strings between two DIFFERENT characters and storing them in an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com