I have this string renders from JSON "I am $1$ frontend developer works at $2$ from $3$".
Now, I want to replace $1$,$2$
and $3$
with dynamic html input text boxes.So, output should be I am
<-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>'));
}
I tried to use string replace method.but seems it will work only for strings.Any other methods can I use to achieve this using 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>');
The result is now:
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>
The regular expression I used is from the comment posted by @n0m4d
You could also try something like this:
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('');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.