admin管理员组文章数量:1405170
I have a string, and I have to insert "div" into the string by using start/end values from an array.
var str = "this is a simple string";
var places = [{
"start": 0,
"end": 3
},
{
"start": 9,
"end": 15
}];
function insert(places, str) {
// I tryed different approaches like this:
str = str.forEach(function(item, index) {
var start = item.start;
var end = item.end;
var newStr = '<div>'+str[start] + '</div>' + str.slice(end);
str = newStr;
});
$('.h').html(str);
// I need to get output str as:
// "<div>this</div> is a <div>simple</div> string"
}
<script src=".1.1/jquery.min.js"></script>
<div class="h"></div>
I have a string, and I have to insert "div" into the string by using start/end values from an array.
var str = "this is a simple string";
var places = [{
"start": 0,
"end": 3
},
{
"start": 9,
"end": 15
}];
function insert(places, str) {
// I tryed different approaches like this:
str = str.forEach(function(item, index) {
var start = item.start;
var end = item.end;
var newStr = '<div>'+str[start] + '</div>' + str.slice(end);
str = newStr;
});
$('.h').html(str);
// I need to get output str as:
// "<div>this</div> is a <div>simple</div> string"
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="h"></div>
How can I do it using splice or foreach functions?
Share Improve this question edited Aug 30, 2016 at 14:30 Mike asked Aug 30, 2016 at 14:18 MikeMike 1473 silver badges14 bronze badges 6- 2 Can you show your code attempt? – MaxZoom Commented Aug 30, 2016 at 14:19
- It'd be nice if your code snippet worked. – evolutionxbox Commented Aug 30, 2016 at 14:23
- It works, it just does nothing because it's not really a code attempt – happymacarts Commented Aug 30, 2016 at 14:23
- @happymacarts It doesn't work. He doesn't have a function name - SyntaxError – user6586783 Commented Aug 30, 2016 at 14:24
- I must have seen it after his edit. – happymacarts Commented Aug 30, 2016 at 14:25
4 Answers
Reset to default 6You could use str
as array of single letters and apply in a loop over places the wanted tags to the letters. Then join all items together and return the string.
This solution works for random sorted places
.
function insert(places, str) {
return places.reduce(function (r, a) {
r[a.start] = '<div>' + r[a.start];
r[a.end] += '</div>';
return r;
}, str.split('')).join('');
}
var str = "this is a simple string",
places = [{ "start": 0, "end": 3 }, { "start": 10, "end": 15 }];
console.log(insert(places, str));
One solution without reduce:
function insert(places, str) {
var r = str.split('');
places.forEach(function (a) {
r[a.start] = '<div>' + r[a.start];
r[a.end] += '</div>';
});
return r.join('');
}
var str = "this is a simple string",
places = [{ "start": 0, "end": 3 }, { "start": 10, "end": 15 }];
console.log(insert(places, str));
For further reading, you could have a look into this answer, why an array of letters might be faster than string functions: How do I replace a character at a particular index in JavaScript?
Assuming that you want to write 0, 4
and 10, 16
(because string 'this'
is of length 4, not 3) it bees
var str = "this is a simple string";
var places = [{
"start": 0,
"end": 4
}, {
"start": 10,
"end": 16
}];
function insert(places, str){
var starts = [], ends = [];
places.forEach(place => {
starts.push(place.start);
ends.push(place.end);
});
return str.split('').map((chr, pos) => {
if(starts.indexOf(pos) != -1) chr = '<div>' + chr;
if(ends.indexOf(pos) != -1) chr = '</div>' + chr;
return chr;
}).join('')
}
console.log(insert(places, str)); // <div>this</div> is a <div>simple</div> string
Here's one way of acplishing your goal, using Array#forEach
and successively mutating the string w/ an 11 chars shift for each <div></div>
tag added.
var str = "this is a simple string";
// change place into an array of objects
var place = [
{
"start": 0,
"end": 3
},
{
"start": 10,
"end": 15
}
];
function insert(place, str) {
var shift = 0;
place.forEach(function(p){
str = str.substring(0,p.start+shift) + "<div>" +
str.substring(p.start+shift,p.end+shift+1) + "</div>" + str.substring(p.end+shift+1);
shift += 11; //shift 11 chars for each match
});
return str;
}
console.log( insert(place,str) );
Note this solution depends upon the places
array holding indices in ascending order.
You might do as follows... though i would remend you to chose your string indices better. Especially it would be better if the end
index doesn't point the last character but the one beyond. I have amended the data accordingly. We are adding an offset of 11 for every round of the reduce since our string gains "<div></div>
" many (11) characters every round.
var str = "this is a simple string";
place = [{
"start": 0,
"end": 4
},
{
"start": 10,
"end": 16
}],
newStr = place.reduce((s,o,i) => s.slice(0,o.start + (i*11)) + "<div>" +
s.slice(o.start + (i*11), o.end + (i*11)) + "</div>" +
s.slice(o.end + (i*11)), str);
console.log(newStr);
Of course it might be generalized to insert any tag.
本文标签: javascriptInsert a tag into string by character indexStack Overflow
版权声明:本文标题:javascript - Insert a tag into string by character index - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744317133a2600319.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论