#86 字体高亮函数


  • 0
    administrators

    请你完成 highlight 函数,可以把模版字符串中的插入内容替换掉,并且插入文档以后显示红色。例如:

    const yourName = 'ScriptOJ'
    const myName = 'Jerry'
    document.body.innerHTML = highlight`Hello, ${yourName}. I am ${myName}.`
    

    上面例子的页面显示如下:

    0_1498033735172_upload-2abd65b1-1e98-46ba-b46f-df4188a036a5

    请你完成 highlight 函数的编写。


  • 0

    const highlight = (tmpl) => {
      return tmpl.replace(/\${(\w+)}/g, function(m1, m2) {
          if (!m2) {
            return '';
          }
          return `<span class="red">${window[m2]}</span>`;
      });
    }
    

    这样写有问题吗?


  • 1

    通过了测试,应该是这样写吧,这题考的是模板字符串

    const highlight = (...args) => {
      let s = ''
      let a = args[0]
      for(let i = 0; i < a.length - 1; i++) {
        s += `${a[i]}<span class=red>${args[i+1]}</span>`
      }
      return s + a[a.length-1]
    }
    

    一个你用了还想用的前端表单验证工具 https://github.com/WLDragon/SMValidator


  • 0

    @ibufu 有啊,highlight`Hello, ${yourName}. I am ${myName}.`,highlight收到的参数不只一个的,看下模块字符串的相关知识


  • 0

    const highlight = (literals, ...values) => {
      var output = "";
      for (var index = 0; index < values.length; index++) {
        output += literals[index] + `<span class="red">${values[index]}</span>`
      }
    
      output += literals[index]
      return output
    }
    

    阮一峰老师教的答案


  • 0

    样式要写在标签上呀,document.body.innerHTML重写了document


  • 0

    const highlight = (section, ...params) => {
    	return section.reduce((res, it, idx) => {
    		return `${res}${it}<span style="color: red">${params[idx] || ''}</span>`
    	}, '')
    }
    

  • 0

    const highlight = function(){
      var args=arguments[0];
      var result=args[0];
      for(var i=1;i<args.length;i++){
        result+=`<span style="color:red">${arguments[i]}</span>${args[i]}`;
      }
      return result;
    }
    

  • 0

    highlight函数里面的字符串数组是修改失败的

    比如

    const highlight = (literals, ...values) => {
      for (var index = 0; index < values.length; index++) {
        literals[index] = literals[index] + `<span class="red">${values[index]}</span>`
      }
      return literals.join('')
    }
    

  • 0

    const highlight = (normalStrs, ...redStrs) => String.raw(normalStrs, ...redStrs.map(s => `<span class="red">${s}</span>`))
    

  • 0

    这题考的是函数解析模板字符串

    .color-red{
      color:red;
    }
    
    const highlight = (arr,...args) => /* TODO */
    {
      let result="";
      arr.forEach((v,i)=>{
        result+=`${arr[i]}<span class="color-red">${args[i]||""}</span>`
      })
      return result
    }
    
    //函数调用
    const yourName = 'ScriptOJ'
    const myName = 'Jerry'
    let html = highlight`Hello, ${yourName}. I am ${myName}.`
    

登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待