【问题标题】:Why JavaStcript str.replace() doesn't work on long HTML strings? [closed]为什么 JavaScript string.replace() 不适用于长 HTML 字符串? [关闭]
【发布时间】:2016-01-18 08:50:47
【问题描述】:

我有很长的 HTML 文件,我使用它转换为字符串

var str = fs.readFile(path, 'utf8', callBabk);

比我想用其他东西替换部分字符串:

str = str.replace('toReplace', 'replaceWithThis');

但这不起作用。

有什么想法吗?

编辑:

完整代码为:

exports.fileToString = function(path){
    return new Promise(function(resolve, reject){
        fs.readFile(path, 'utf8', function(err, data) {
            if (err) {
                return reject(err);
            }
            return resolve(data);
        });
    });
};

然后在另一个文件中:

var htmlString = '';
Promise.all([
 htmlString = fileUtils.fileToString('../file.html'),
]).then(function() {
 htmlString = htmlString.replace('toReplace', 'replaceWithThis');
 console.log('htmlString: ' + htmlString); //This never prints
}. reject);

【问题讨论】:

  • 添加完整代码。 minimal reproducible example
  • 如果你想替换所有出现的文本,你需要使用正则表达式与g标志/toReplace/g
  • 另外 readFile 不返回字符串,你在回调中得到字符串形式。

标签: javascript node.js string


【解决方案1】:

fs.readFile() 不会返回它读取的数据,因此您的代码:

var str = fs.readFile(path, 'utf8', callBabk);

完全错误。 fs.readFile() 是一个异步函数,其结果仅在您传递给它的回调中可用。

fs.readFile(path, 'utf8', function(err, data) {
    var str;
    if (!err) {
        str = data.replace(/toReplace/g, 'replaceWithThis');
        // now do something with the modified string
    }
});

附:如果你想替换所有出现的给定字符串(不仅仅是第一个匹配),你还需要正则表达式上的g 标志。

【讨论】:

  • @user3887119 - 这个答案对你有用吗?
【解决方案2】:
// read the file
fs.readFile('./myfile.html', function read(err, data) {
    if (err) {
        throw err;
    }
processContent(data)
});
//replace the strings
function processFile(content) {
    var str = content.replace(/toReplace/g, 'replaceWithThis');
    console.log(str);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多