Reputation: 814
I'm trying to search for a certain word in a string data but it only returns the first match.
const searchFunc = (stringData, searchedType) => {
const regex = new RegExp(`${searchedType}(.*)`, "g");
var arr = regex.exec(stringData);
while (arr !== null) {
prefix = arr[1].replace(/[`_:'",.]/gi, "")
return prefix;
}
};
i call the search function in another one like this :
searchFunc(data, "path");
my strinData is like this :
{
path: '/aaa',
...
},
{
path: '/bbb',
...
},
},
{
path: '/ccc',
...
},
The output i get :
=> /aaa
The output i want
=> /aaa
=> /bbb
=> /ccc
Upvotes: 0
Views: 49
Reputation: 370879
Create an array to put the results in, then push
to that array in every iteration of the while
loop, and return the array at the end of the function:
const searchFunc = (stringData, searchedType) => {
const pattern = new RegExp(`${searchedType}(.*)`, "g");
const results = [];
let match;
while (match = pattern.exec(stringData)) {
results.push(match[1].replace(/[`_:'",.]/gi, ""));
}
return results;
};
const data = `routes: [
{
path: '/aaa',
xxx: {
...
},
},
{
path: '/bbb',
xxx: {
...
},
},
{
path: '/ccc',
xxx: {
...
},
},
],`
const prefixValue = searchFunc(data, "path");
console.log(`prefix found => ${prefixValue}`);
Note that this is an X/Y problem: ideally, fix whatever's serving you that string so that it gives you proper JSON instead, so that you can parse it into an object and use object/array manipulation methods instead, for example:
const searchFunc = (data, prop) => data.map(obj => obj[prop]);
const dataArr = [{
path: '/aaa',
xxx: {},
},
{
path: '/bbb',
xxx: {},
},
{
path: '/ccc',
xxx: {},
},
];
const prefixValue = searchFunc(dataArr, "path");
console.log(`prefix found => ${prefixValue}`);
Upvotes: 1