Categories
JavaScript Answers

How to Compare 2 Strings Alphabetically for Sorting Purposes with JavaScript?

Sometimes, we want to compare 2 strings alphabetically for sorting purposes with JavaScript.

In this article, we’ll look at how to compare 2 strings alphabetically for sorting purposes with JavaScript.

Compare 2 Strings Alphabetically for Sorting Purposes with JavaScript with the localeCompare Method

We can compare 2 strings alphabetically for sorting with the localeCompare method.

For instance, we can write:

const arr = ['foo', 'bar', 'baz']
const sorted = arr.sort((a, b) => a.localeCompare(b))
console.log(sorted)

to use localeCompare to compare strings a and b in the comparator callback we pass into the sort method.

It’ll return -1 is a before b alphabetically, 0 if they’re the same, and 1 otherwise.

Then we get that sorted is:

["bar", "baz", "foo"]

as a result.

Conclusion

We can compare 2 strings alphabetically for sorting with the localeCompare method.

Categories
JavaScript Answers

How to Listen to Input Value Change with JavaScript?

We can listen to input value change with JavaScript with the addEventListener method.

For instance, if we have the following input:

<input type="text" name="name" value="" />

Then we can listen for changes in the value inputted by writing:

const input = document.querySelector('input')  
input.addEventListener('change', (e) => {  
  console.log(e.target.value);  
});

We get the input element with document.querySelector .

Then we call addEventListener with 'change' to listen to the change event.

The 2nd argument of addEventListener is an event listener function that lets us get the input value with e.target.value.

Now when we type in the input box and move focus away from it, we see the inputted value logged.

Categories
JavaScript Answers

How to Set Custom HTML5 Required Field Validation Message with JavaScript?

We can set custom HTML5 required field validation messages with the setCustomValidity method.

For instance, if we have the following input:

<form>
  <input type="email" pattern="[^@]*@[^@]" required  />
  <input type="submit" />
</form>

Then we can set a custom validation message by writing:

const input = document.querySelector('input')
input.addEventListener('invalid', (e) => {
  e.target.setCustomValidity('Put here custom message')
})

We get the input with document.querySelector .

Then we listen to the invalid event with addEventListener .

Then we call e.target.setCustomValidity on it with our own validation error message.

e.target is the input element since we called addEventListener on the input .

Categories
JavaScript Answers

How to Add Line Breaks into the HTML5 Canvas with fillText?

We can split the text string by the line breaks and position the split text in a way that each piece of text is on a separate line.

To do this, we write:

<canvas width='200' height='200'></canvas>

to add the canvas.

Then we write:

const c = document.querySelector('canvas').getContext('2d');
c.font = '11px Courier';
const txt = 'line 1\nline 2\nthird line..';
const x = 30;
const y = 30;
const lineheight = 15;
const lines = txt.split('\n');

for (let i = 0; i < lines.length; i++) {
  c.fillText(lines[i], x, y + (i * lineheight));
}

to add the txt text into the canvas.

We get the 2D context with querySelector and getContext .

Then we set the font property to the font we want.

Next, we have the txt text with some line breaks.

We set the x and y variables to the position of the text for the first line.

Then we call split to split txt by the line breaks into an array.

Finally, we use a for loop to call fillText on each lines entry with the y coordinates of the line incremented by each line with y + (i * lineheight) .

Now we should see each line of text display on its own line.

Categories
JavaScript Answers

How to Find the HTML Label Element Associated with a Given Input with JavaScript?

We can use the labels property of the input to get the label associated with the input.

For instance, if we have the following HTML:

<div>  
  <label for='name'>name</label>  
  <input name='nameInput' id='name'>  
</div>

Then we can get the input with the given label by writing:

const input = document.querySelector('input')  
console.log(input.labels)

We get the input with document.querySelector .

Then we get the label elements for the input with the labels property.

The for attribute value of the label should match up with the id attribute of the input for them to be associated with each other.

input.labels should return a NodeList with the label elements for the input.