2016-08-01 44 views
0

我有这个字符串从JSON呈现“我是$ 1 $前端开发人员在$ 2 $从$ 3 $开始工作”。使用javascript替换字符串到html内容

现在,我想通过动态HTML输入文本boxes.So更换$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>')); 
} 

我试图用字符串替换method.but看来,这只能用于strings.Any其他方法可以用来实现这个使用javascript/jquery

+0

你可以发表你的代码,无论你尝试过什么。 – Manish

+0

你可以证明,你的尝试是什么? – Satpal

+1

如果你想要通过复选框替换这些$ number $,请试试这个''我是$ 1 $前端开发者,工作价格是$ 3 $ $ 2 $。“replace(/ \ $ \ d \ $/g,'') – n0m4d

回答

0
<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> 
0
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

0

注释您也可以尝试这样的事:

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(''); 
}