Reputation: 65
I currently have a form and what I would like is that every time a "Tag" is mentioned, denoted by being surrounded by double square brackets (i.e [[Tag]]), the same tag is repeated once.
This would mean that when I type [[Tag]]
, I would immediately see [[Tag]][[Tag]]
. This idea is that someone would then be able to type text in between the two tags.
I have the following JavaScript:
function newNote() {
const note_button = document.getElementById("new_note_button")
const note = document.getElementById("new_note_form_container");
if (note.style.display === "none") {
note.style.display = "block";
note_button.innerHTML = "Only show notes"
} else {
note.style.display = "none";
note_button.innerHTML = "Create a new note"
}
}
document.addEventListener('DOMContentLoaded', function(){
let input_note = document.getElementById('note_text');
input_note.addEventListener('input', upThing)
})
function upThing(ev) {
let note_form = ev.target.value;
let regex = /(?=\[\[).*?(?<=\]\])/g;
let first_position = 0;
let result = note_form.substring(first_position);
let open_bracket = result.indexOf("[[") + 2;
let close_bracket = result.indexOf("]]");
if (close_bracket > open_bracket) {
let tag = result.substring(open_bracket, close_bracket);
console.log(tag)
ev.target.value = ev.target.value + "[[" + tag + "]]";
}
}
This JavaScript does produce the desired [[Tag]]
to [[Tag]][[Tag]]
. However, every time I continue to type another [[Tag]]
appears. So this does not serve the purpose.
I need it so that I can repeat this process for [[Tag 2]], [[Tag 3]] etc.
It would be helpful to understand how to move the tags to bold when enclosed by [[ ]]
Upvotes: 1
Views: 40
Reputation: 19493
This will work when the ]]
is at the end of string. This can be extended to any position though.
Update: should work even if on middle of text.
document.querySelector('.btex').addEventListener('keyup', function(ev) {
if (ev.key == ']') {
var val = this.value;
var start = this.selectionStart;
if (start > 1 && val.substring(start - 2, start) == "]]") {
var pos = val.lastIndexOf("[[", start);
var word = val.substring(pos, pos + start);
if (start > pos) {
var end = this.selectionEnd;
this.value = val.substring(0, start) + word + val.substring(end);
this.selectionStart = this.selectionEnd = start;
return false;
}
}
}
});
<textarea class="btex" rows="4" style="width:100%"></textarea>
Upvotes: 1