繁体   English   中英

使用javascript将字符串替换为html内容

[英]Replace String to html content using javascript

我从JSON获得了此字符串渲染“我是$ 1 $的前端开发人员,从$ 3 $到$ 2 $”。

现在,我想用动态html输入文本框替换$1$,$2$$3$ ,所以输出应该是

<-input textbox here> frontend developer works at <-input textbox here> from <-input textbox here>.

var str = "I am $1$ frontend developer works at $2$ from $3$";
var newStr = "";
for(var i=0;i<3;i++){
var id = '$'+i+'$';
if (str.indexOf(id) >= 0){
   newStr = str.replace(id, $.parseHTML('<div><input type="text" 
id="input-"+i/></div>'));
}

我尝试使用字符串替换方法。但似乎它仅适用于字符串。我可以使用其他任何方法来使用javascript / jquery实现此目的

    <div id="div1">
    </div>

    <script type="text/javascript">
var data = "I am $1$ frontend developer works at $2$ from $3$";
     //include jQuery before this code
      $(function(){
        data.replace('$1$','<input type="text" />').replace('$2$','<input type="text" />').replace('$3$','<input type="text" />');
       });

   $('#div1').html(data);
    </script>
var input = "I am $1$ frontend developer works at $2$ from $3$";
var result = input.replace(/\$\d\$/g, '<div><input type="text" id="input-"+i/></div>');

现在的结果是:

I am <div><input type="text" id="input-"+i/></div> frontend developer works at <div><input type="text" id="input-"+i/></div> from <div><input type="text" id="input-"+i/></div>

我使用的正则表达式来自@ n0m4d发表的评论

您也可以尝试如下操作:

var input = "I am $1$ frontend developer works at $2$ from $3$";
var result = replaceWithInputTags(input, '$')

function replaceWithInputTags(source, templateChar){
   var sourceArgs = source.split(templateChar);

   return sourceArgs.map(function(item){
       var index = +item;
       if (isNaN(index)) return item;
       return "<input type='text' id='input-" + (index-1) + "' />";       
   }).join('');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM