2016-08-01 83 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(''); 
}