代码之家  ›  专栏  ›  技术社区  ›  Code Maniac

如何在$变量_的每个实例上拆分``(反勾号字符串)

  •  1
  • Code Maniac  · 技术社区  · 6 年前

    所以我的问题是如何用 backtick 在变量的每个实例上。

    我尝试过 \${.*?} 但这不起作用,因为 ${variable} 将首先替换为变量值,然后执行拆分函数。

    知道怎么做吗?

    let a = 2
    let b = 4
    let x = `Superman${a}hello${b}one more`.split(/\${.*?}/g)
    
    console.log(x)

    旁侧: 我不想把它包装成“或”的解决方案。

    console.log('`Superman${a}hello${b}one more`'.split(/\${.*?}/g))
    3 回复  |  直到 6 年前
        1
  •  1
  •   Intervalia    6 年前

    为了澄清我对原始问题的评论,这里有一个默认模板文本函数的示例:

    function defaultTemplateLiteralFn(strs, ...args) {
      return strs.map((str, idx) => str+(args[idx]||'')).join('');
    }
    
    const test = "special test";
    const a = 10;
    const b = 432;
    console.log(`This is a ${test}. "${a}+${b}=${a+b}"`)
    console.log(defaultTemplateLiteralFn`This is a ${test}. "${a}+${b}=${a+b}"`)

    当您使用标记模板(即:您不提供处理模板文本的函数)时,该语言提供了一个默认函数,该函数执行与我在函数中执行的类似的操作。 defaultTemplateLiteralFn 上面。它返回字符串与值的组合部分。

    示例函数获取字符串的每个部分,并将适当的值放在字符串之后。如果没有值,则使用空字符串。

        2
  •  3
  •   tkausl    6 年前

    行执行后,无法获取原始模板字符串。但是,可以使用标记函数/标记模板文本来获取字符串的各个部分,包括替换值:

    function Test() {
      console.log(arguments)
      return arguments.length - 1
    }
    
    let a = 2
    let b = 4
    let c = Test `Superman${a}hello${b}one more`
    console.log(`This template string has ${c} substituted values`)
        3
  •  0
  •   Code Maniac    6 年前

    我所做的一种方法是使用模板文本。我在一个叫 styled-components 它允许我们用JS编写CSS。

    如果有的话,还想看看其他的方法吗?

    function splitOnVariable(str, age){
      // first argument to function will always be array of strings provided in input string.
      return str
    }
    
    let a = 1;
    let b = 2;
    
    console.log(splitOnVariable`hello${a} break me on variable${b} !!!`)