Categories
JavaScript Answers

How to define regex for empty string or white space with JavaScript?

To define regex for empty string or white space with JavaScript, we can use the \s+ pattern.

For instance, we write

const regex = /^\s+$/;

to define a regex that matches a string with all spaces by using ^ to match the start of the string, \s+ to match spaces, and $ to match the end of the string.

Categories
JavaScript Answers

How to add an InfoWindow to each marker with JavaScript Google Maps API v3?

To add an InfoWindow to each marker with JavaScript Google Maps API v3, we set the info property of the marker.

For instance, we write

const marker = new google.maps.Marker({
  map,
  position: point,
  clickable: true,
});

marker.info = new google.maps.InfoWindow({
  content: `<b>Speed:</b>: ${values.inst} knots`,
});

google.maps.event.addListener(marker, "click", () => {
  marker.info.open(map, marker);
});

to create a marker with the Marker constructor.

Then we set its info property to an InfoWindow instance which has the content set to some text.

And then we add a marker click listener with addListener to open the info window with marker.info.open when we click on the marker.

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.