Vee Jay Tan
Vee Jay Tan

Reputation: 79

How to format input in html using javascript

How to format input text on html, sample input: Hi hello

I like to display the input like this

'Hi','hello',

When I hit enter, single quote with a comma will automatically display.

Any suggestion? Thank you.

Upvotes: 0

Views: 1661

Answers (3)

Maik Lowrey
Maik Lowrey

Reputation: 17556

The text is then formatted and returned to the input field. You only need an eventlistener, a function that converts the text.

const input = document.getElementById('watch');
input.addEventListener('keypress', function (e) {
    e.preventDefault();
    if (e.key === 'Enter') {
      input.value = input.value.split(' ').map(s => `'${s}'`).toString() + ',';
    }
  return false;
});
<form>
  <input type="text" value="Hi World" id="watch">  
</form>

Upvotes: 1

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can use split and join

const str = "Hi hello";
let output = '';
if(str)
     output = `'${str.split(" ").join("','")}',`;
 console.log(str);

Upvotes: 1

Johnni O.
Johnni O.

Reputation: 121

const string = 'a b c'
console.log(string.split(' ').map(str => `'${str}'`).toString() + ',')

Upvotes: 0

Related Questions