简体   繁体   English

如何在 Node JS 中搜索和替换字符串

[英]How can i search and replace strings in Node JS

I am trying to write some code which allows me to pass a doc as a string which is either plain txt or html and has some fields embeded i want to replace with personal values.我正在尝试编写一些代码,它允许我将文档作为字符串传递,该字符串可以是纯 txt 或 html,并且嵌入了一些我想用个人值替换的字段。 something like for example like this像这样的东西

Hi {{ first_name | fallback: "there" }},

i will pass the field names as an object with same name so the lookup is easy.我将字段名称作为具有相同名称的对象传递,以便查找很容易。 So what i am looking for coding ideas how to search for the {{ }} part and then check if field is not unknown, null or "" and if it is apply the fallback value in the tag.所以我正在寻找编码想法如何搜索 {{ }} 部分,然后检查字段是否未知、null 或 "" 以及是否在标签中应用回退值。 This is something like mailmerge but i dont want ths to be a docx file and output as word or pdf.这有点像mailmerge,但我不希望这是一个docx文件并输出为word或pdf。 i just want the processed string so i can pass back to my mail code and send message我只想要处理过的字符串,这样我就可以传回我的邮件代码并发送消息

Program that will do the following to achieve your output,将执行以下操作以实现您的输出的程序,

  1. Get the string enclosed between {{}}获取包含在{{}}之间的字符串
  2. Split the sting by |分裂刺|
  3. Remove unwanted space using trim()使用trim()删除不需要的空间
  4. Check and find the fallback value检查并找到fallback
  5. Replace the sting with desired value用所需的值Replace刺痛

Here is the example program that will do the above operation on step by step.下面是示例程序,它将逐步执行上述操作。

var str = 'Hi {{ first_name | fallback: "there" }},'
var data = {
    first_name: "siva",
    last_name: "sankar",
    code: 29
}

function templateRender(str, data) {
    return str.replace(/{{([^}]+)}}/g, function (match, string) {
        var fallback = ''
        var stringArr = string.split("|");
        var value = stringArr[0].trim();

        if (stringArr[1]) { fallback = stringArr[1].match(/(?<=fallback\:\s?)(["'].*?["'])/)[0].replace(/["']/g, "").trim(); }
        return data[value] ? data[value] : fallback;
    });
}

console.log("New String :::: ", templateRender(str, data));

Look at HandlebarsJs.看看 HandlebarsJs。 It is exactly what Handlebars does, https://handlebarsjs.com这正是 Handlebars 所做的, https: //handlebarsjs.com

For your fallback you can use if.对于您的后备,您可以使用 if。

{{#if first_name}}{{first_name}}{{else}}there{{/if}},

Which will default to there if first_name is falsey.如果 first_name 为 falsey,则默认为那里。

If you think if is a bit verbose you can write a helper function for defaults.如果您认为 if 有点冗长,您可以为默认值编写一个辅助函数。

Handlebars.registerHelper('fallback', (val, def) => val || def);

and use it in a template并在模板中使用它

Hi {{fallback first_name 'there'}},

 const template = Handlebars.compile(`Hi {{#if first_name}}{{first_name}}{{ else }}there{{/if}},`); console.log(template({ first_name: '' })); console.log(template({ first_name: 'Billy' })); Handlebars.registerHelper('fallback', (val, def) => val || def); const templateWithFallback = Handlebars.compile(`Hi {{fallback first_name 'there'}},`); console.log(templateWithFallback({ first_name: '' })); console.log(templateWithFallback({ first_name: 'Billy' }));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.0/handlebars.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在节点 js 的搜索框中连接两个字符串? - How could i concatenate two strings in my search box in node js? 如何在node.js中搜索? - How do i search in node.js? 如何使用 rollup-replace 替换多个字符串 - How can I replace multiple strings with rollup-replace 如何使用node.js在JSON中向数组添加字符串? - How can I add strings to an array in a JSON using node.js? 如何搜索{{。*}}并替换为json - How can I search for {{.*}} and replace with json 如何将quoted-printable内容解码为node.js中的普通字符串? - How can I decode quoted-printable content to normal strings in node.js? 搜索和替换字符串而不使用正则表达式而是循环,如何一次替换多个单词? - Search and replacing strings without using Regex but loops instead, how can I replace more than one word at a time? Node.js。 如何用Async Await语法替换“ return new Promise”? - Node.js. How can I replace 'return new Promise' with Async Await syntax? 如何始终将某个路径参数替换为 node.js 中的另一个值? - How can I always replace a certain path parameter to another value in node.js? 如何使用流媒体在大文本文件中的节点 js 中找到并用空格替换所有标点符号? - How can I find and replace all punctuation with space in node js in large text file using streaming?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM