How can I do string interpolation in JavaScript?

前端 未结 19 2528
慢半拍i
慢半拍i 2020-11-21 07:54

Consider this code:

var age = 3;

console.log(\"I\'m \" + age + \" years old!\");

Are there any other ways to insert the value of a variabl

19条回答
  •  粉色の甜心
    2020-11-21 08:14

    Custom flexible interpolation:

    var sourceElm = document.querySelector('input')
    
    // interpolation callback
    const onInterpolate = s => `${s}`
    
    // listen to "input" event
    sourceElm.addEventListener('input', parseInput) 
    
    // parse on window load
    parseInput() 
    
    // input element parser
    function parseInput(){
      var html = interpolate(sourceElm.value, undefined, onInterpolate)
      sourceElm.nextElementSibling.innerHTML = html;
    }
    
    // the actual interpolation 
    function interpolate(str, interpolator = ["{{", "}}"], cb){
      // split by "start" pattern
      return str.split(interpolator[0]).map((s1, i) => {
        // first item can be safely ignored
    	  if( i == 0 ) return s1;
        // for each splited part, split again by "end" pattern 
        const s2 = s1.split(interpolator[1]);
    
        // is there's no "closing" match to this part, rebuild it
        if( s1 == s2[0]) return interpolator[0] + s2[0]
        // if this split's result as multiple items' array, it means the first item is between the patterns
        if( s2.length > 1 ){
            s2[0] = s2[0] 
              ? cb(s2[0]) // replace the array item with whatever
              : interpolator.join('') // nothing was between the interpolation pattern
        }
    
        return s2.join('') // merge splited array (part2)
      }).join('') // merge everything 
    }
    input{ 
      padding:5px; 
      width: 100%; 
      box-sizing: border-box;
      margin-bottom: 20px;
    }
    
    *{
      font: 14px Arial;
      padding:5px;
    }
    
    

提交回复
热议问题