Categories
JavaScript Answers

How to Use Regular Expression to Get Strings Between Parentheses with JavaScript?

Sometimes, we may want to get the substrings in a JavaScript string that is between parentheses.

In this article, we’ll look at how to use regular expressions to get strings between parentheses with JavaScript.

Use Regular Expression to Get Strings Between Parentheses with JavaScript

We can use the match method to get the substrings in a string that match the given regex pattern.

For instance, we can write:

const txt = "I expect five hundred dollars ($500). and new brackets ($600)";
const regExp = /\(([^)\+)\)/g;
const matches = [...txt.match(regExp)];
console.log(matches)

We create the regExp regex that matches anything between parentheses.

The g flag indicates we search for all substrings that matches the given pattern.

Then we call match with the regExp to return an array of strings that are between the parentheses in txt .

Therefore, matches is [“($500)”, “($600)”] .

We can also exclude strings with inner parentheses with:

/\(([^()\]*)\)/g

With the matchAll method, we can also get the substrings that are inside the parentheses without the parentheses.

To use it, we write:

const txt = "I expect five hundred dollars ($500). and new brackets ($600)";
const regExp = /\(([^)\]+)\)/g;
const matches = [...txt.matchAll(regExp)].flat();
console.log(matches)

We call flat to flatten the array.

And so matches is [“($500)”, “$500”, “($600)”, “$600”] .

Conclusion

We can use regular expressions to get strings between parentheses with JavaScript.

Categories
JavaScript Answers

How to Get the Value of a Checked Checkbox with JavaScript?

Sometimes, we may want to get the value of a checked checkbox within our web app.

In this article, we’ll look at how to get the value of a checked checkbox with JavaScript.

Get All Checked Checkboxes

We can use plain JavaScript to get all the checked checkboxes.

For instance, if we have the following checkboxes:

<input type="checkbox" value="1" name="mailId[]" checked>1
<input type="checkbox" value="2" name="mailId[]" checked>2
<input type="checkbox" value="3" name="mailId[]">3

Then we can select all the checkboxes that are checked and get their values with:

const checked = document.querySelectorAll('input[type="checkbox"]:checked');
console.log([...checked].map(c => c.value))

We add the :checked pseudoselector to select all the checked checkboxes.

The first 2 checkboxes have the checked attribute, so we should get the value of the first 2 with it.

Then we log the value property.

We spread the checked NodeList into an array.

Then we call map with a callback to return the value property of each checkbox that is checked.

Therefore, the console log should log [“1”, “2”] .

Conclusion

We can get the value of all the checked checkboxes with plain JavaScript.

Categories
JavaScript Answers

How to Sort Alphanumeric Strings with JavaScript?

Sometimes, we want to sort alphanumeric strings with JavaScript.

In this article, we’ll look at how to sort alphanumeric strings with JavaScript.

String.prototype.localeCompare

We can use the string localeCompare method to compare strings so we can sort them.

For instance, we can write:

const arr = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12',
]
const sorted = arr.sort((a, b) => {
  return a.localeCompare(b, undefined, {
    numeric: true,
    sensitivity: 'base'
  })
})
console.log(sorted)

We call localeCompare to compare a and b naturally.

We set numeric to true to compare the numerical part of a and b .

sensitivity is set to 'base' to compare the case and the alphabet.

Therefore, sorted is:

["19asd", "123asd", "12345asd", "asd12", "asd123"]

Use Intl.Collator

Also, we can use the Intl.Collator constructor to create a collator instance which has the compare method to compare 2 strings.

For instance, we can write:

const arr = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12',
]
const collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: 'base'
});
const sorted = arr.sort((a, b) => {
  return collator.compare(a, b)
})
console.log(sorted)

The options are the same as localeCompare .

compare takes the 2 strings we want to compare.

Then sorted is the same result as before.

Conclusion

We can sort alphanumeric strings naturally with native JavaScript methods.

Categories
JavaScript Answers

How to Get an Element’s Top Position Relative to the Browser’s Viewport?

Sometimes, we may want to get an element’s top position relative to the browser’s viewport.

In this article, we’ll look at ways to get an element’s top position relative to the browser’s viewport.

Use the getBoundingClientRect Method

We can use the getBoundingClientRect method to get an element’s position relative to its viewport.

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
console.log(t, l)

We get the div with querySelector .

Then we call getBoundingClientRect on it to get an object with the top and left properties.

top has the position relative to the top of the viewport.

left has the position relative to the left side of the viewport.

Both are in pixels.

If we want to take scrolling into account, then we add the scrollY value to top and scrollX value to left .

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
const {  
  scrollX,  
  scrollY  
} = window  
const topPos = t + scrollX  
const leftPos = l + scrollY  
console.log(topPos, leftPos)

to include the scroll position with the element’s position.

Conclusion

We can get the element’s position relative to the viewport by using the getBoundingClientRect method.

Categories
JavaScript Answers

How to Show or Hide a div Using JavaScript?

Sometimes, we may want to show or hide a div in our web app.

In this article, we’ll look at how to show or hide a div with JavaScript.

Manipulate the style.display Property

To show or hide a div with JavaScript, we can manipulate the style.display property to change the CSS display property.

We show the div if we set it to 'block' , 'inline' , or 'inline-block' .

'block' makes it block level, 'inline' makes it inline. 'inline-block' is like block except that it doesn’t add a line break after the element.

And we hide it if we set it to 'none' .

For instance, we can write the following HTML:

<button id='show'>
  show
</button>
<button id='hide'>
  hide
</button>

<div>
  hello
</div>

Then we can write the following JavaScript code to toggle the display property of the div:

const showBtn = document.querySelector('#show')
const hideBtn = document.querySelector('#hide')
const div = document.querySelector('div')

showBtn.addEventListener('click', () => {
  div.style.display = 'block'
})
hideBtn.addEventListener('click', () => {
  div.style.display = 'none'
})

We get the show and hide buttons and the div with document.querySelector .

Then we call addEventListener with the 'click' argument to add click listeners to the buttons.

When we click on showBtn , we set div.style.display to 'block' .

And when we click on hideBtn , we set div.style.display to 'none' .

Manipulate the style.visibility Property

We can also change the value of the style.visibility property to show or hide a div.

The difference between display and visibility is that display adds or remove the div from the screen when we change its value.

visibility keeps the space of the element regardless of whether it’s shown or hidden.

For example, we can write:

const showBtn = document.querySelector('#show')
const hideBtn = document.querySelector('#hide')
const div = document.querySelector('div')

showBtn.addEventListener('click', () => {
  div.style.visibility = 'visible'
})
hideBtn.addEventListener('click', () => {
  div.style.visibility = 'hidden'
})

and keep the HTML the same as the previous example.

'visible' makes the div visible and 'hidden' makes it hidden.

Show or Hide a Collection of Elements

We can show or hide a collection of elements easily with JavaScript.

For instance, if we have the following HTML:

<button id='show'>
  show
</button>
<button id='hide'>
  hide
</button>

<div>
  hello
</div>
<div>
  world
</div>

Then we can loop through each div to show and hide them.

To do this, we write the following JavaScript:

const showBtn = document.querySelector('#show')
const hideBtn = document.querySelector('#hide')
const divs = document.querySelectorAll('div')

showBtn.addEventListener('click', () => {
  for (const div of divs) {
    div.style.display = 'block'
  }
})
hideBtn.addEventListener('click', () => {
  for (const div of divs) {
    div.style.display = 'none'
  }
})

We get the buttons the same way as the previous examples.

Then we get both divs with querySelectorAll .

In the click listeners, we loop through the divs and set the style.display property for each div.

We can do the same thing with the visibility property.

Conclusion

We can show or hide one or more divs with JavaScript easily.