【问题标题】:Replace with multiple value in string - Typescript用字符串中的多个值替换 - 打字稿
【发布时间】:2018-05-27 09:39:51
【问题描述】:

问题:

var str = "I have a <animal>, a <flower>, and a <car>.";

现在我想用 Tiger、Rose 和 BMW 替换上面的字符串

<animal> , <flower> and <car> 

请为此建议最佳方法。

我正在使用 Typescript 开发 Angular 2 应用程序。

【问题讨论】:

标签: javascript html angular typescript angular5


【解决方案1】:

如果您使用 Typescript,您应该根据 https://www.typescriptlang.org/docs/handbook/basic-types.htmllet str = 'I have a &lt;animal&gt;, a &lt;flower&gt;, and a &lt;car&gt;.'; 声明您的字符串注意单引号,这是 Angular 样式指南的推荐(例如,使用 ng lint 连续强制执行)交付管道)。

您可以替换代码中已有的占位符,而不是用常见的 javascript 替换方法替换:

Screenshot code see the backticks here

【讨论】:

    【解决方案2】:

    您可以使用带有替换函数的正则表达式来评估每个匹配项并返回适当的替换项。

    var str = "I have a <animal>, a <flower>, and a <car>.";
    
    function replace(source : string, replacements : { [name:string]: string }) {
        return str.replace(  new RegExp("<([A-z]*)>", "g"), (m) => {
            return replacements[m.substring(1, m.length -1)];
        });
    }
    
    console.log(replace(str, {
        "animal" : "Tiger",
        "flower" : "Rose",
        "car" : "BMW"
    }))
    

    【讨论】:

    • 或者不那么冗长,函数体可以是:return str.replace(/&lt;([A-z]*)&gt;/g, m =&gt; replacements[m.substring(1, m.length - 1)]);
    • @Duncan 你这样更短,但由于它是一个较长的表达式,我认为它在多行中看起来更好
    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多