i have a contenteditable div where i want to make it so that when a user types in a hashtag, everything between that hashtag and the next space will be wrapped in
<span class="tag"></span>
for example, if a user types in "hi, my name is john #sweaters are a cool article of clothing" the html would read
hi my name is <span class="tag">#john</span> are a cool article of clothing
so far i've got this in my javascript but i think don't know where to go from here
$('.post_box').keydown(function(){
var note = $(this).html();
var hashtagPattern = /[#]/i;
var spacePattern = /[ ]/i;
// find hashtag
// find space
// get stuff between them
var tag = stuff between them;
tag.wrap('<span class=\"tag\" contenteditable=\"false\"/>');
});
I tried to get what you mean, although I can't understand why you disappeared "sweater" and placed the hashtag to "john", but, suppose that you have this:
hi my name is john are a cool article of clothing
and someone adds a hashtag on "john" like this:
hi my name is #john are a cool article of clothing
the html should be something like this:
hi my name is <span class="tag">#john</span> are a cool article of clothing
I made a modification to your script
$('.post_box').keyup(function(){
var note = $(this).html(), pattern = /\s\#[A-Za-z0-9]+\s/gi, tag;
while(tag = pattern.exec(note)){
note = note.replace(tag.toString(),' <span class=\"tag\" contenteditable=\"false\">'+$.trim(tag.toString())+'</span> ');
}
$(this).html("");
$(this).html(note);
});
if you notice this line:
note = note.replace(tag.toString(),' <span class=\"tag\" contenteditable=\"false\">'+$.trim(tag.toString())+'</span> ');
you'll realize that is wrapping the hashtag between the , of course there is still a lot of thing to do in order to make this code something usable (at least that's what I think), but that is entirely up to you.
you can find the test code here TEST
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.