不使用正则,实现ES6的模板字符串,javascript

134 阅读1分钟

题目描述:

设计一个函数,该函数类似模板字符串的功能,可以实现对字符串中模板的替换,要求不能使用正则替换.

测试用例:

// 不使用正则实现ES6模板字符串
const template = My name is ${name},I'm from ${city}, I'm ${age}, I ${action} basketball, He play ${some}ball, this {test} info; 

const result = strWrap(template, {name: 'LiuXing', city: 'Beijing', action: 'play'}); 

console.log(result); // My name is LiuXing,I'm from Beijing, i'm --, I play basketball, He play --ball. 

实现方法:


function strWrap(template,options){
   while (template.includes('${')){
      const preIndex = template.indexOf('${');
      const afterIndex = template.indexOf('}');
      const select = template.substring(preIndex+2,afterIndex);
      const replaceStr = options[select];
      if(replaceStr){
         template = template.replace('${'+select+'}',replaceStr)
      }else {
         template = template.replace('${'+select+'}','--')
      }
   }
   return template
}