Categories
JavaScript Answers

How to get the sha1 hash of a string in Node.js?

To get the sha1 hash of a string in Node.js, we can use the crypto module.

For instance, we write

const crypto = require("crypto");
const shasum = crypto.createHash("sha1");
shasum.update("foo");
const digest = shasum.digest("hex");

to call crypto.createHash to create the shasum hash object.

Then we call shasum.update to update the hash with the 'foo' string.

And then we return the hash digest with digest.

Categories
JavaScript Answers

How to encode HTML entities in JavaScript?

To encode HTML entities in JavaScript, we can use the string replace and charCodeAt methods.

For instance, we write

const encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, (i) => {
  return "&#" + i.charCodeAt(0) + ";";
});

to call replace with a regex pattern that we want to look for in rawStr and a callback does the replacement.

In the callback, we get each result and replace them with the HTML entity with the character code that we get with i.charCodeAt(0).

We prepend "&#" and append ';' to the character code to form the entity.

Conclusion

To encode HTML entities in JavaScript, we can use the string replace and charCodeAt methods.

Categories
JavaScript Answers

How to get next / previous element using JavaScript?

To get next / previous element using JavaScript, we can use the nextSibling and previousSibling properties.

For instance, we write

<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>

to add 3 divs.

Then we write

document.getElementById("foo2").nextSibling;
document.getElementById("foo2").previousSibling;

to get the next and previous sibling of the div with ID foo2 with nextSibling and previousSibling.

Conclusion

To get next / previous element using JavaScript, we can use the nextSibling and previousSibling properties.

Categories
JavaScript Answers

How to remove auto slide on Bootstrap Carousel with JavaScript?

To remove auto slide on Bootstrap Carousel with JavaScript, we call carousel with an object.

For instance, we write

$(".carousel").carousel({
  interval: false,
});

to call carousel with an object that has interval set to false to disable auto slide on the Bootstrap carousel when creating it.

Categories
Vue Answers

How to pass props as initial data in Vue.js?

To pass props as initial data in Vue.js, we can set the prop value as an initial value of a reactive property.

For instance, we write

<script>
export default {
  //...
  props: {
    record: {
      type: Object,
      required: true,
    },
  },

  data() {
    return {
      recordLocal: { ...this.record },
    };
  },
  //...
};
</script>

to set the recordLocal reactive property to a copy of the record prop as its initial value.

We register the record prop in the props property.