在 nodejs 中是否可以檢測 txt 檔案中相同字串的多次出現?
我當前的代碼如下
const fs = require('fs');
var file_path = 'file.txt';
fs.readFile(file_path, "UTF-8", (error, data) => {
if (error) throw error;
else {
if (data.includes('Test Value')) {
console.log(data.indexOf('Test Value'))
}
fs.close(file, (err) => {
if (err)
console.error('Failed to close file', err);
else {
console.log("\n> File Closed successfully");
}
});
}
});
在 file.txt 中,我有以下內容
Value1
Value2
Test Value
Value3
Test Value
Value4
當我運行上面的代碼時,我只能檢測到“測驗值”的第一次出現,而我需要檢測 file.txt 中所有出現的“測驗值”,請幫忙
uj5u.com熱心網友回復:
indexOf有兩個引數。您可以使用存盤最后一個位置并在下一個位置繼續下一個搜索:
const fs = require('fs');
var file_path = 'file.txt';
fs.readFile(file_path, "UTF-8", (error, data) => {
if (error) throw error;
else {
for (let pos = data.indexOf('Test Value'); pos > -1; pos = data.indexOf('Test Value', pos 1)) {
console.log(pos);
}
fs.close(file, (err) => {
if (err)
console.error('Failed to close file', err);
else {
console.log("\n> File Closed successfully");
}
});
}
});
例子:
const data = `Value1
Value2
Test Value
Value3
Test Value
Value4`;
for (let pos = data.indexOf('Test Value'); pos > -1; pos = data.indexOf('Test Value', pos 1)) {
console.log(pos);
}
uj5u.com熱心網友回復:
.exec()您可以通過 RegExp方法使用正則運算式全域搜索(多個匹配項) 。
使用 String.match()方法的全域搜索只回傳匹配項而不回傳索引。但是 RegExp.exec()方法回傳索引。
let match;
let search = /Test Value/g; // <-- the 'g' flag is important!
// If you need to construct the regexp dynamically
// do = new RegExp('Test Value', 'g')
while (match = search.exec(data)) {
console.log(match.index);
}
uj5u.com熱心網友回復:
是的。遍歷data陣列并檢查每個資料元素。
const fs = require('fs');
var file_path = 'file.txt';
fs.readFile(file_path, "UTF-8", (error, data) => {
if (error) throw error;
else {
data.split('\n').forEach(line => {
if (line === 'Test Value') {
console.log(data.indexOf(line))
}
})
fs.close(file, (err) => {
if (err)
console.error('Failed to close file', err);
else {
console.log("\n> File Closed successfully");
}
});
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463745.html
標籤:javascript 节点.js 文件 异步 承诺
