Categories
JavaScript Answers

How to check if a string is a float with JavaScript?

To check if a string is a float with JavaScript, we can use the isNaN function.

For instance, we write

if (!isNaN(value) && value.toString().includes(".")) {
  console.log("this is a float.");
}

to check if value is a number by negating the boolean returned by isNaN.

And then we check if a decimal point is included by converting value to a string with toString and call the includes method on the string.

If both are true, then value is a float.

Categories
JavaScript Answers

How to escape single quotes in JavaScript string for JavaScript evaluation?

To escape single quotes in JavaScript string for JavaScript evaluation, we use the string replace method.

For instance, we write

const escaped = searchKeyword.replace(/'/g, "\\'");

to call replace with the regex for single quotes and a string for the escaped single quotes to replace the single quotes in searchKeyword with the escaped version and return the escaped string.

Categories
JavaScript Answers

How to create and clone a JSON object with JavaScript?

To create and clone a JSON object with JavaScript, we can use the spread operator.

For instance, we write

const newJsonObj = { ...jsonObj };

to shallow copy the properties of the jsonObj object into a new object and assign the new object to newJsonObj.

Categories
JavaScript Answers

How to add a dotted stroke in the JavaScript canvas?

To add a dotted stroke in the JavaScript canvas, we call the setLineDash method.

For instance, we write

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");

ctx.setLineDash([5, 10]);

ctx.beginPath();
ctx.lineWidth = "2";
ctx.strokeStyle = "green";
ctx.moveTo(0, 75);
ctx.lineTo(250, 75);
ctx.stroke();

to call setLineDash with the dash stroke lengths.

Then we call beginPath to start drawing.

We set the line width by setting lineWidth.

We set the stroke color by setting strokeStyle.

Then we draw by calling moveTo with the start point.

We call lineTo to draw to the end point.

And we call stroke to stop drawing.

Categories
JavaScript Answers

How to calculate median with JavaScript?

To calculate median with JavaScript, we can sort the numbers and get the middle value.

For instance, we write

const median = (numbers) => {
  const sorted = Array.from(numbers).sort((a, b) => a - b);
  const middle = Math.floor(sorted.length / 2);

  if (sorted.length % 2 === 0) {
    return (sorted[middle - 1] + sorted[middle]) / 2;
  }

  return sorted[middle];
};

console.log(median([4, 5, 7, 1, 33]));

to define the median function.

In it, we call sort on the copied numbers array after copying it with Array.from to sort the numbers in ascending order.

Then we check if the length of the sorted array is event.

We get the middle index by taking the floor of the length divided by 2.

If it is, then we take the average of the 2 middle numbers.

Otherwise, we return the middle number.