RoyKeane94
RoyKeane94

Reputation: 65

Every time a word enclosed by "" is typed in an input field, repeat it using JavaScript

I am trying to write some JavaScript so that every time I type a word enclosed by "", the word including the "" is instantly repeated whilst typing.

For example, when typing "Interesting", the input field would immediately display "Interesting.

It would need to work each type "" was used, so that it could be used many times in the input field.

I have the following code to automatically capitalise letters when typing in a input field:

document.addEventListener('DOMContentLoaded', function(){
    let input_note = document.getElementById('note_text');
    input_note.addEventListener('input', upThing)
})

function upThing(ev){
    ev.target.value = ev.target.value.toUpperCase();
}

This may provide a starting point but is still a long way off.

Upvotes: 0

Views: 161

Answers (3)

Nora
Nora

Reputation: 650

You can use a Regular Expression to match for the quotes and then join the matches together in the label.

I also advice you change your real-time text transformation to be done through CSS instead of JavaScript, this is because if you change the value of an input while the client has their input position a few characters behind the last character, it'll be reset to the end.

const noteInput = document.getElementById("note-text");
const noteQuotes = document.getElementById("note-quotes");

noteInput.addEventListener("input", (event) => {
  noteQuotes.innerText = Array.from(event.target.value.toUpperCase().matchAll(/"(.*?)"/gm), (match) => match[0]).join(", ");
});
#note-text {
  text-transform: uppercase;
}
<input id="note-text" type="text">

<p id="note-quotes"></p>

Edit: I may have misunderstod your question. :)

Upvotes: 2

imvain2
imvain2

Reputation: 15857

My answer checks the last character to verify its a quote. Then determine if its the first quote or not by setting the value of the start variable. Then if its the last quote, append the value and reset the start variable.

let input_note = document.getElementById('note_text');
let start = -1;

input_note.addEventListener('input', upThing)

function upThing(ev){
    let obj = ev.target
    isQuote = (obj.value[obj.value.length-1] == "\"")
    
    if(isQuote && start == -1){
      start = obj.value.length;
    }
    else if(isQuote && start > -1){
      obj.value += " " + obj.value.slice(start,obj.value.length-1)
      start = -1;
    }
    
}
#note_text {
  text-transform: uppercase;
}
<input id="note_text" type="text">

Upvotes: 0

savvy
savvy

Reputation: 101

I would use REGEX expression to match the value from the input to begin with You can look up the regex expressions here

Upvotes: 0

Related Questions