Categories
JavaScript Answers

How to Detect URLs in a JavaScript String and Convert them to Links?

Use a Regex to Find URLs in a String

We can create our own function that uses a regex to find URLs.

For instance, we can write:

const urlify = (text) => {
  const urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(urlRegex, (url) => {
    return `<a href="${url}">${url}</a>`;
  })
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)

We create the urlify functioon that takes a text string.

In the function, we refine the urlRegex variable that has the regex for matching URLs.

We check for http or https .

And we look for slashes and text after that.

The g flag at the end of the regex lets us search for all URLs in the string.

Then we call text.replace with the urlRegex and return a string with the matched url in the callback.

Therefore, when we call urlify with text , we get:

'Find me at <a href="http://www.example.com>http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>'

as a result.

We can make the URL search more precise with a more complex regex.

For instance, we can write:

const urlify = (text) => {
  const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, (url) => {
    return `<a href="${url}>${url}</a>`;
  })
}
const text = 'Find me at http://www.example.com and also at http://stackoverflow.com';
const html = urlify(text);
console.log(html)

We search for http , https , ftp , and file URLs.

And we also include : , letters, ampersands, and underscores in the pattern.

Categories
JavaScript Answers

How to Swap Two Variables in JavaScript?

Sometimes in our JavaScript code, we’ve to swap the values of 2 variables in our code.

In this article, we’ll look at ways to swap 2 variables’ values in JavaScript.

Using Destructuring Syntax

One way to swap the value of 2 variables is to use the destructuring syntax.

For instance, we can write:

let a = 5,
  b = 6;
[a, b] = [b, a];
console.log(a, b);

We defined the a and b values which are 5 and 6 respectively.

Then in the 3rd line, we use the destructuring to swap their values.

On the right side, we put b and a into an array.

Then on the right side, we destructure the array entries by putting a and b on .the array on the left side.

So a is 6 and b is 5 when we long the values of a and b on the last line.

Using a Temporary Variable

We can also use a temporary variable to help swap the values of 2 variables.

To use it, we write:

let a = 1,
  b = 2,
  tmp;
tmp = a;
a = b;
b = tmp;
console.log(a, b);

We defined a and b which are 1 and 2 respectively.

Next, we assign a to the tmp temporary variable.

Then we assign b to a .

And finally, we assign the tmp to b to update b with the previous value of a .

Therefore, a is now 2 and b is 1.

Conclusion

We can swap the value of 2 variables with JavaScript by using the restructuring syntax or using a temporary variable.

Categories
JavaScript Answers

How to Format a Number with K at the End if it is One Thousand or More and Show the Number Otherwise in JavaScript?

Sometimes, we want to format a number so that we show K at the end if it’s a thousand or more and return the show number if it’s less than 1000.

In this article, we’ll look at how to format a number with K at the end if it’s 1000 or more and return the whole number otherwise.

Use Math Methods

We can create our own function that use Math methods to check if a number is 1000 or bigger in absolute value.

If it is, then we divide by 1000 and add a K after it.

Otherwise, we return the whole number.

To do this, we write:

const kFormatter = (num) => {
  return Math.abs(num) > 999 ? Math.sign(num) * ((Math.abs(num) / 1000).toFixed(1)) + 'k' : Math.sign(num) * Math.abs(num)
}

console.log(kFormatter(1200));
console.log(kFormatter(-1200));
console.log(kFormatter(900));
console.log(kFormatter(-900));

We create the kFormatted function that takes the num number parameter.

Then we check if num is bigger than 999 in absolute value.

Math.abs lets us compute the absolute value of a number.

If it’s bigger than 999, then we use Math.sign to get the sign of the number.

Math.sign return -1 if the number is negative and 1 otherwise.

Then we multiply that by the absolute value of num divided by 1000.

And then we call toFixed with 1 to return a string version of the number rounded to one decimal place.

Then we add 'k' after it.

Otherwise, we just return the number itself with:

Math.sign(num) * Math.abs(num)

So we get:

1.2k
-1.2k
900
-900

from the console log results.

Conclusion

We can use various Math methods to format numbers to return a truncated number if it’s 1000 or more and return the whole number otherwise.

Categories
JavaScript Answers

How to Use the toLocaleTimeString Method to Return a Formatted Date and Time String Without Including the Seconds?

Sometimes, we want to format a JavaScript date object into a time string but omit the seconds from the string.

In this article, we’ll look at ways to use the toLocaleTimeString method to return a formatted time string without including the seconds in the string.

Set hour and minute to 2-digit

We can set the hour and minute properties to '2-digit' to get rid of the seconds from the returned time string.

For instance, we can write:

const dateWithoutSecond = new Date();
const formatted = dateWithoutSecond.toLocaleTimeString([], {
  hour: '2-digit',
  minute: '2-digit'
});
console.log(formatted)

We create a Date instance and store it in the dateWithoutSecond variable.

Then we call toLocateString on it with an object with the hour and minute options set to '2-digit' to return a time string without the seconds.

So formatted would be a string like '04:05 PM’ .

Set timeStyle to short

We can also set the timeStyle option to short to omit the seconds from the returned time string.

For instance, we can write:

const dateWithoutSecond = new Date();
const formatted = dateWithoutSecond.toLocaleTimeString([], {
  timeStyle: 'short'
});
console.log(formatted)

to do this.

Then formatted is something like '4:07 PM’ .

Conclusion

We can set various options with toLocateTimeString to return a time string without the seconds part.

Categories
JavaScript Answers

How to Check for text-overflow Ellipsis in an HTML Element?

Sometimes, we want to check whether the text-overflow ellipsis is rendered in the element.

In this article, we’ll look at how to check for the text-overflow ellipsis in an HTML element.

Check if offsetWidth is Less than scrollWidth

The offsetWidth property of an element tells us the width of the element rendered on the screen.

scrollWidth tells us the width of the element including the truncated parts.

Therefore, we can see if a piece of text is truncated with the CSS text-overflow property by checking whether offsetWidth is less than scrollWidth .

For instance, if we have the following HTML:

<div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in neque laoreet, venenatis quam id, tristique ipsum. Sed augue ipsum, pharetra in ipsum eget, varius placerat odio. Pellentesque a luctus metus, commodo placerat elit. Nullam efficitur augue in magna consectetur finibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras porttitor lectus pretium, placerat nulla eget, hendrerit magna. Nunc in sem dui. Sed sollicitudin sem a massa malesuada cursus. Mauris feugiat enim sit amet efficitur lobortis.
</div>

And CSS:

div {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Then we can do the check by writing:

const isEllipsisActive = (e) => {
  return (e.offsetWidth < e.scrollWidth);
}

const div = document.querySelector('div')
console.log(isEllipsisActive(div))

We do the comparison between offsetWidth and scrollWidth as we specified in the isEllipsisActive function.

Then we get the div with querySelector and pass it into the isEllipsisActive .

So the console log should log true since we truncated the text with the CSS.

Conclusion

We can check if a piece of text is truncated with the CSS text-overflow property by checking whether the offsetWidth of the element is less than its scrollWidth .