Categories
JavaScript Answers

How to Match an Exact String with JavaScript?

Sometimes, we want to find an exact string within our JavaScript code.

In this article, we’ll look at how to find an exact string with JavaScript.

Using the String.prototype.match Method

We can use the JavaScript string instance’s match method to search for a string that matches the given pattern.

For instance, we can write:

const str1 = 'abc'
const str2 = 'abcd'
console.log(str1.match(/^abc$/))
console.log(str2.match(/^abc$/))

to call match with a regex that matches the exact word.

^ is the delimiter for the start of the word.

And $ is the delimiter for the end of the word.

Therefore, the regex matches the exact word in between the delimiters.

The first console log should log 'abc' as a match.

And the 2nd console log should log null .

We can convert the matched strings to an array.

For instance, we can write:

const str1 = 'abc'
console.log([...str1.match(/^abc$/)])

We use the spread operator to convert the match object to an array since the match object is an iterable object.

Conclusion

We can match an exact string with JavaScript by using the JavaScript string’s match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

Categories
JavaScript Answers

How to Remove Insignificant Trailing Zeros from a JavaScript Number?

Sometimes, we want to remove insignificant trailing zeroes from a JavaScript number.

In this article, we’ll look at ways to remove insignificant trailing zeroes from a JavaScript number.

Using the Number.prototype.toString Method

We can convert a number to a number string with the JavaScript number’s toString method.

The toString method will remove any insignificant trailing zeroes from the number.

For instance, if we have:

const n = 1.245000  
const noZeroes = n.toString()  
console.log(noZeroes)

Then noZeroes is '1.245' .

Using the Number.prototype.toFixed Method

We can use the JavaScript number to toFixed method to convert a number into the number string with the number of decimal places we want to show.

Then we can convert it back to a number with the parseFloat or Number functions.

For instance, we can write:

const n = 1.245000  
const noZeroes = parseFloat(n.toFixed(5));  
console.log(noZeroes)

We call toFixed with 5 to return a number with 5 decimal places.

The toFixed method automatically discards the insignificant trailing zeroes.

After that, we use parseFloat to convert the number string back to a number.

Therefore, we get the same result as the previous example.

We can replace parseFloat with Number by writing:

const n = 1.245000  
const noZeroes = Number(n.toFixed(4));  
console.log(noZeroes)

and get the same result.

Conclusion

To remove insignificant trailing zeroes from a number, we can call toFixed or toString to convert it to a number string.

And to convert the number string back to a number, we can use the parseFloat or Number functions.

Categories
JavaScript Answers

How to Disable Browser Print Options (Headers, Footers, Margins) from the Page?

Sometimes, we want to disable the headers, footers, and margins when a web page is being printed.

In this article, we’ll look at ways to disable the headers, footers, and margins on the page when it’s being printed.

Disable Headers, Footers, and Margins with CSS

We can disable headers, footers, and margins with CSS.

For instance, we can write:

<!doctype html>
<html>

<head>
    <title>Print Test</title>
    <style type="text/css" media="print">
      @page {
        size: auto;
        margin: 0mm;
      }

      html {
        background-color: #FFFFFF;
        margin: 0px;
      }

      body {
        border: solid 1px blue;
        margin: 10mm 15mm 10mm 15mm;
      }

     </style>
  </head>

  <body>
    <div>Top line</div>
    <div>Line 2</div>
  </body>

</html>

We set some styles for the page when being printed with the @page CSS directive.

We set the size to auto and set margin to 0mm to remove the margins.

Then we set the html styles to a white background color and no margins.

And in the body, we set the border and margin styles.

We set the media attribute to print to make sure the styles are only applied when the page is being printed.

Conclusion

We can disable various parts of the page when they’re printed with printing specific CSS styles.

Categories
JavaScript Answers

How to Avoid Browser Popup Blockers with JavaScript Code?

Sometimes when we try to open a window with the window.open method, we may see the browser permission popup asking for permission to open the popup created by window.open .

In this article, we’ll look at how to avoid browser popup blockers within our JavaScript code.

Avoid Calling window.open in Async Functions

To avoid the permission popup for opening the popup, we should use avoid calling window.open in a function that returns a promise or in callbacks for functions like setTimeout , setInterval , or any other async function.

This is because, a popup can only be opened from an app without permission with direct user action.

The depth of the call chain may also matter since some older browsers requires permission is window.open isn’t called by the function that’s run immediately after a user action.

Therefore, we should call window.open within synchronous functions run as a result of direct user action to avoid the popup permission popup from showing in any browser.

We can check if a popup is blocked by checking if window.open returns null or undefined .

For instance, we can check if a popup window is blocked by writing:

const pop = (url, w, h) => {
  const popup = window.open(url, '_blank', 'toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width=500,height=500');
  return popup !== null && typeof popup !== 'undefined'
}
console.log(pop('https://example.com'))

We call window.open with the url as the first argument and a string with some settings as the 3rd argument.

Then we return is popup isn’t null and popup isn’t undefined .

If the popup opens, then popup shouldn’t be null and it shouldn’t be undefined .

And so pop should return true if the popup opens.

Conclusion

We can avoid browser popup blockers by calling window.open in a synchronous function.

Categories
JavaScript Answers

How to Convert a JavaScript String camelCase to Capital Case?

Sometimes, we want to convert a JavaScript string from camel case to capital case with JavaScript.

In this article, we’ll look at how to convert a JavaScript string from camel case to capital case.

Use the String.prototype.replace Method

We can use the JavaScript string replace method to insert a space between all the words starting with a capital and replace a string’s first character with the upper case version of the character.

To do this, we write:

const str = "thisStringIsGood"
  .replace(/([A-Z])/g, ' $1')
  .replace(/^./, (str) => {
    return str.toUpperCase();
  })
console.log(str)

We call replace with the /([A-Z])/g regex and $1 to add a space before each word that starts with a capital letter.

The g flag gets all instance of strings that match the given pattern.

Then we call replace again to convert the first character of each word to the upper case of the letter.

Therefore, str is:

'This String Is Good'

Use the String.prototype.split and String.prototype.join Methods

Another way to convert a camel case string into a capital case sentence is to use the split method to split a string at the start of each word, which is indicated by the capital letter.

Then we can use join to join the words with a space character.

To do this, we write:

const splitCamelCaseToString = (s) => {
  return s
    .split(/(?=[A-Z])/)
    .map((p) => {
      return p[0].toUpperCase() + p.slice(1);
    })
    .join(' ');
}
const str = splitCamelCaseToString("thisStringIsGood")
console.log(str)

We call split with the /(?=[A-Z])/ regex to split the string into words where the capital letter indicates the start of the word.

Then we call map to convert the string to start with an upper case letter.

And then we call join to join each word together with a space character.

Therefore, str is:

'This String Is Good'

Conclusion

We can use various string and array methods to convert a string from camel case to a capital case sentence.