Categories
JavaScript Answers

How to Split a String Only the at the First n Occurrences of a Delimiter?

Sometimes, we want to split a string only the at the first n occurrences of a delimiter.

In this article, we’ll look at how to split a string only the at the first n occurrences of a delimiter.

Split a String Only the at the First n Occurrences of a Delimiter

To split a string only the at the first n occurrences of a delimiter, we can use the split method with the JavaScript array’s splice and join methods.

For instance, we write:

const string = 'Split this, but not this'
const arr = string.split(' ')
const result = arr.splice(0, 2)

result.push(arr.join(' '));
console.log(result)

We call split on the whole string.

Then we call splice to with 0 and 2 to get the first 2 items from the arr array and assign it to result.

The items returned by splice are removed from arr.

Next, we call arr.join with the remaining substrings in the arr array with a space to join them together.

Finally, we call result.push on that string to add that string to result.

Therefore, result is ['Split', 'this,', 'but not this'] according to the console log.

Conclusion

To split a string only the at the first n occurrences of a delimiter, we can use the split method with the JavaScript array’s splice and join methods.

Categories
JavaScript Answers

How to Mask a US Phone Number String with JavaScript?

Sometimes, we want to mask a US phone number string with JavaScript.

In this article, we’ll look at how to Mask a US phone number string with JavaScript.

Mask a US Phone Number String with JavaScript

To Mask a US phone number string with JavaScript, we can match the different parts of the phone number with a regex that has capturing groups.

For instance, we write:

<input type="text" id="phone" placeholder="(555) 555-5555" />

to add the input.

Then we write:

document.getElementById('phone').addEventListener('blur', (e) => {
  const x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
  e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});

to select the phone input with document.getElementById('phone').

Then we call addEventListener with 'blur' to listen to the blur event.

The blur event is emitted when we move focus out of the input.

In the event handler, we call replace on the input value to replace all non digit substrings with empty strings.

Then we call match to match the digit groups of a phone number.

Then we set the e.target.value to the phone number with the parentheses and dashes.

x has the digit groups.

Now when we type in a phone number, we should see the parentheses and dashes added to the groups.

Conclusion

To Mask a US phone number string with JavaScript, we can match the different parts of the phone number with a regex that has capturing groups.

Categories
JavaScript Answers

How to Check if a JavaScript Array Contains Duplicate Values?

Sometimes, we want to check if a JavaScript array contains duplicate values.

In this article, we’ll look at how to check if a JavaScript array contains duplicate values.

Check if a JavaScript Array Contains Duplicate Values

To check if a JavaScript array contains duplicate values, we can use the JavaScript array some and indexOf methods.

For instance, we write:

const arr = [11, 22, 11, 22];
const hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
console.log(hasDuplicate)

to check if arr has duplicate values.

We call some with a callback to check if some array entries matches the condition returned by the callback.

indexOf returns the index of the first element that matches a given value.

So if indexOf returns a value that isn’t equal to the index i, we know that the value is a duplicate.

Therefore, the console log should log true.

Conclusion

To check if a JavaScript array contains duplicate values, we can use the JavaScript array some and indexOf methods.

Categories
JavaScript Answers

How to Add Hover CSS Attributes Via jQuery and JavaScript?

Sometimes, we want to add hover CSS attributes via jQuery and JavaScript.

In this article, we’ll look at how to add hover CSS attributes via jQuery and JavaScript.

Add Hover CSS Attributes Via jQuery and JavaScript

To add hover CSS attributes via jQuery and JavaScript, we can call the jQuery mouseenter and mouseleave methods on the selected element.

For instance, if we have:

<div id='some-content'>
  hello world
</div>

Then we write:

$("#some-content")
  .mouseenter(function() {
    $(this).css("background", "#F00").css("border-radius", "3px");
  }).mouseleave(function() {
    $(this).css("background", "").css("border-radius", "0px");
  });

We select the div with:

$("#some-content")

Then we call mouseenter with a callback that calls css to set the background and border radius on the div when our mouse enters the div.

Likewise, we call mouseleave with a callback that calls css to set the background and border radius on the div when our mouse leaves the div.

Now when we move our mouse in and out of the div, we see different styles applied to the div.

Conclusion

To add hover CSS attributes via jQuery and JavaScript, we can call the jQuery mouseenter and mouseleave methods on the selected element.

Categories
JavaScript Answers

How to Convert a JavaScript Object to an Array and Sort it?

Sometimes, we want to convert a JavaScript object to an array and sort it.

In this article, we’ll look at how to convert a JavaScript object to an array and sort it.

Convert a JavaScript Object to an Array and Sort it

To convert a JavaScript object to an array and sort it, we can use the Object.entries method to return an array of key value pairs, then use JavaScript array’s map method to return an array with the object values.

Then we can use the JavaScript array sort method to sort the returned entries.

For instance, we write:

const data = {
  1: {
    displayName: "Dude1",
    email: "dude1@example.com<mailto:dude1@example.com>",
    lastActive: 1296980700,
    level: 57,
    timeout: 12969932837
  },
  2: {
    displayName: "Dude2",
    email: "dude2@example.com<mailto:dude2@example.com>",
    lastActive: 1296983456,
    level: 28,
    timeout: 12969937382
  },
  3: {
    displayName: "Dude3",
    email: "dude3@example.com<mailto:dude3@example.com>",
    lastActive: 1296980749,
    level: 99,
    timeout: 129699323459
  }
}

const arr = Object
  .entries(data)
  .map(([key, obj]) => {
    return {
      ...obj,
      index: key
    }
  })
  .sort((x, y) => {
    return x.index - y.index
  });
console.log(arr)

to convert the data object into an array and the sort the entries.

We call Object.entries to return an array of key-value pairs in the data object.

Then we call map with a callback that merges obj with the index set to the key and apply this operation to each entry.

Next, we call sort with a callback that returns x.index - y.index to sort the entries.

As a result, arr is:

[
  {
    "displayName": "Dude1",
    "email": "dude1@example.com<mailto:dude1@example.com>",
    "lastActive": 1296980700,
    "level": 57,
    "timeout": 12969932837,
    "index": "1"
  },
  {
    "displayName": "Dude2",
    "email": "dude2@example.com<mailto:dude2@example.com>",
    "lastActive": 1296983456,
    "level": 28,
    "timeout": 12969937382,
    "index": "2"
  },
  {
    "displayName": "Dude3",
    "email": "dude3@example.com<mailto:dude3@example.com>",
    "lastActive": 1296980749,
    "level": 99,
    "timeout": 129699323459,
    "index": "3"
  }
]

Conclusion

To convert a JavaScript object to an array and sort it, we can use the Object.entries method to return an array of key value pairs, then use JavaScript array’s map method to return an array with the object values.

Then we can use the JavaScript array sort method to sort the returned entries.