Given this string:
var str = 'One two three four five';
and this parameters:
position: 8
length: 5
I would like to wrap the part of the string that starts at the given position and has the given length inside SPAN tags. In this case, I want this result:
'One two <span>three</span> four five'
How can this be done most elegantly?
Update: My own solution is here: http://jsfiddle.net/simevidas/XjbvN/
var str = 'One two three four five';
var position = 8
var length = 5
var newstr=str.slice(0,position)+'<span>'+str.slice(position,position+length)+'</span>'+str.slice(position+length);
str.substr(0, position)
+ "<span>"
+ str.substr(position, length)
+ "</span>"
+ str.substr(position + length, str.length)
Not sure if this is what you mean by elegant...
The concept of most elegant is likely subjective.
Most simply :
var str = 'One two three four five';
var position = 8;
var length = 5;
var newStr = str.substr(0, position) + '<span>' + str.substr(position, length) + '</span>' + str.substr(position + length);
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.