Categories
JavaScript Answers jQuery

How to Remove Hyphens from a JavaScript String?

To remove hyphens from a JavaScript string, we can call the JavaScript string’s replace method.

For instance, we can write:

const str = "185-51-671";  
const newStr = str.replace(/-/g, "");  
console.log(newStr)

We call replace with a regex that matches all dashes with /-/ .

The g flag matches all instances of the pattern.

Then we replace all of them with empty strings as specified in the 2nd argument.

Therefore, newStr is '18551671' .

Categories
JavaScript Answers jQuery

How to Add Infinite Scrolling with jQuery?

To add infinite scrolling with jQuery, we can detect when we scrolled to the bottom of the page with the scroll method.

To do this, we write the following HTML to contain our content:

<div id="lipsum">
</div>

Then we can add some content into the div when we scrolled to the bottom of the page by writing:

const arr = [...Array(30)].fill().map((_, i) => i)
for (const n of arr) {
  $('#lipsum').append(`<p>${n}</p>`)
}

$(window).scroll(() => {
  if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
    for (const n of arr) {
      $('#lipsum').append(`<p style='background-color: red'>${n}</p>`)
    }
  }
});

We first add some content to the div with:

const arr = [...Array(30)].fill().map((_, i) => i)
for (const n of arr) {
  $('#lipsum').append(`<p>${n}</p>`)
}

Then we detect when we scroll to the bottom of the page by calling $(window).scroll with a callback.

In the callback, we check if we scrolled to the bottom of the page with:

$(window).scrollTop() >= $(document).height() - $(window).height() - 10

And if that’s true , we add some content with the for-of loop.

scrollTop gets the scroll position of the page.

And $(document).height() — $(window).height() — 10 is the position at the bottom of the page in pixels.

Now we should see new content displayed when we scrolled to the bottom of the page.

Categories
JavaScript Answers

How to Select a Span Containing a Specific Text Value Using jQuery?

To select a span containing a specific text value using jQuery, we can select all the spans and then use the filter method to find the one with the given text value.

For instance, if we have the following HTML:

<div>
  <span>FIND ME</span>
  <span>dont find me</span>
</div>

and we want to find the span with the text FIND ME , then we can write:

const findMe = [...$("span")].filter((el) => {
  return $(el).text().includes('FIND ME')
})
console.log(findMe)

We call $(“span”) to get all the spans.

Then we spread the spans into an array with the spread operator.

Next, we call filter with a callback that takes the el element and calls text on the element once it’s put into the $ function to get the text.

Then we call includes with 'FIND ME' to check for the text.

This will find the span that has FIND ME anywhere in the element.

If we want to find an exact match, we write:

const findMe = [...$("span")].filter((el) => {
  return $(el).text() === 'FIND ME'
})

In either case, it’ll return an array with the span with the text FIND ME .

Categories
JavaScript Answers

How to Check if a JavaScript Global Variable Exists?

To check if a JavaScript global variable exists, we can check whether the variable isn’t undefined or use the hasOwnProperty with window to check whether the global variable has been added.

For instance, we can write:

if (window.someVar === undefined) {
  window.someVar = 123456;
}

if (!window.hasOwnProperty('someVar')) {
  window.someVar = 123456;
}

to add an if statement to check whether window.someVar is undefined .

If it is, then we set the someVar global variable to 123456.

Another way to check if the someVar global variable exists is with the hasOwnProperty method.

If window.hasOwnProperty is called with 'someVar' and that returns false , then we know that it doesn’t exist.

If it doesn’t exist, then we set window.someVar to 123456. s

Categories
JavaScript Answers

How to Round Time to the Nearest Quarter-Hour in JavaScript?

To round time to the nearest quarter-hour in JavaScript, we can use existing JavaScript date methods.

For instance, we can write:

const roundTimeQuarterHour = (time) => {
  const timeToReturn = new Date(time);
  timeToReturn.setMilliseconds(Math.round(timeToReturn.getMilliseconds() / 1000) * 1000);
  timeToReturn.setSeconds(Math.round(timeToReturn.getSeconds() / 60) * 60);
  timeToReturn.setMinutes(Math.round(timeToReturn.getMinutes() / 15) * 15);
  return timeToReturn;
}
const dt = new Date(2021, 1, 1, 1, 13, 1, 1)
console.log(roundTimeQuarterHour(dt))

to create the roundTimeQuarterHour function that takes the time to round.

In the function, we convert that to a date object with the Date constructor top create the timeToReturn date object.

Then we call setMilliseconds to set timeToReturn the nearest 1000 milliseconds.

Next, we call setSeconds to round timeToReturn to the nearest 60 seconds.

Then, we call setNMinutes to round timeToReturn to the nearest 15 minutes by getting the number of minutes from the time with getMinutes , dividing that by 15 and multiplying that by 15 again.

Therefore, the console log should log:

Mon Feb 01 2021 01:15:00 GMT-0800 (Pacific Standard Time)