Add 2 new articles
This commit is contained in:
41
blog_posts/js-edit-url-params.md
Normal file
41
blog_posts/js-edit-url-params.md
Normal file
@ -0,0 +1,41 @@
|
||||
---
|
||||
title: "Tip: Edit URL Parameters in JavaScript"
|
||||
shortTitle: Edit URL Parameters
|
||||
type: tip
|
||||
tags: javascript,string
|
||||
expertise: intermediate
|
||||
author: chalarangelo
|
||||
cover: blog_images/sofia-tram.jpg
|
||||
excerpt: Avoid the naive approach and use a more robust method to edit URL parameters in JavaScript.
|
||||
firstSeen: 2022-12-07T05:00:00-04:00
|
||||
---
|
||||
|
||||
Editing the query string of a URL in JavaScript is pretty common. While the naive approach of directly editing the URL as a string often works, it's a fragile solution that can break easily. This is especially true when working with encoding, hash fragments and other such intricacies.
|
||||
|
||||
The most robust way to go about editing a URL is using the `URL` interface to parse the original URL string and edit it as necessary. This way, the browser will take care of all the complicated details and make the code easier to read and maintain.
|
||||
|
||||
```js
|
||||
const urlString = 'https://mysite.com?p=42&from=home#details';
|
||||
const url = new URL(urlString);
|
||||
|
||||
// Delete a parameter
|
||||
const removedParam = 'from';
|
||||
url.searchParams.delete(removedParam);
|
||||
|
||||
// Edit/add parameters
|
||||
const newParams = {
|
||||
p: 57,
|
||||
track: 'none'
|
||||
};
|
||||
Object.keys(newParams).forEach(key => {
|
||||
url.searchParams.set(key, newParams[key]);
|
||||
});
|
||||
|
||||
// Edit the hash fragment
|
||||
const newHash = 'new';
|
||||
url.hash = newHash;
|
||||
|
||||
console.log(`${url}`); // https://mysite.com?p=57&track=none#new
|
||||
```
|
||||
|
||||
As you can see in the example, the `URL` interface provides a number of methods to edit the URL. The most commonly used ones are `URL.searchParams` and `URL.hash`. The former is a `URLSearchParams` object that provides methods to edit the query string of the URL, while the latter is a string that contains the hash fragment of the URL. Apart from these two, the `URL` interface also provides methods to edit the protocol, host, port, path, etc. of the URL.
|
||||
49
blog_posts/js-locale-sensitive-string-truncation.md
Normal file
49
blog_posts/js-locale-sensitive-string-truncation.md
Normal file
@ -0,0 +1,49 @@
|
||||
---
|
||||
title: How can I truncate a string accounting for locale?
|
||||
shortTitle: Locale-sensitive string truncation
|
||||
type: question
|
||||
tags: javascript,string
|
||||
expertise: advanced
|
||||
author: chalarangelo
|
||||
cover: blog_images/reflection-on-lake.jpg
|
||||
excerpt: Locale-sensitive string splitting and truncation are finally possible in JavaScript.
|
||||
firstSeen: 2022-12-04T05:00:00-04:00
|
||||
---
|
||||
|
||||
Breaking a string into words is not the easiest, neither is finding a good place to add an ellipsis. Part of the problem is recognizing word boundaries and words themselves. Luckily `Intl.Segmenter` is a relatively new object that enables locale-sensitive text segmentation.
|
||||
|
||||
`Intl.Segmenter` allows you to specify a locale and a `granularity` option to specify how a string should be segmented. The `granularity` option can be set to `'grapheme'`, `'word'` or `'sentence'` according to your needs. Using `Intl.Segmenter.prototype.segment()` on a string returns an iterable `Segments` object. This can then be used to find the correct index to split a string without being in the middle of a word or a sentence.
|
||||
|
||||
```js
|
||||
const str =
|
||||
'The quick brown fox jumps over the lazy dog. The jay, pig, fox, zebra and my wolves quack!';
|
||||
const cutOff = 50;
|
||||
|
||||
const wordSegmenter = new Intl.Segmenter('en-US', { granularity: 'word' });
|
||||
const sentenceSegmenter = new Intl.Segmenter('en-US', {
|
||||
granularity: 'sentence',
|
||||
});
|
||||
|
||||
let lastWordBreak = -1;
|
||||
for (let word of wordSegmenter.segment(str)) {
|
||||
if (word.isWordLike) continue;
|
||||
if (word.index >= cutOff) break;
|
||||
lastWordBreak = word.index;
|
||||
}
|
||||
str.slice(0, lastWordBreak) + '...';
|
||||
// 'The quick brown fox jumps over the lazy dog. The...'
|
||||
|
||||
let lastSentenceBreak = -1;
|
||||
for (let sentence of sentenceSegmenter.segment(str)) {
|
||||
if (
|
||||
lastSentenceBreak !== -1 &&
|
||||
sentence.index + sentence.segment.length >= cutOff
|
||||
)
|
||||
break;
|
||||
lastSentenceBreak = sentence.index + sentence.segment.length;
|
||||
}
|
||||
str.slice(0, lastSentenceBreak).trim().slice(0, -1) + '...';
|
||||
// 'The quick brown fox jumps over the lazy dog...'
|
||||
```
|
||||
|
||||
Note that the `Intl.Segmenter` object is not yet supported in all environments at the time of writing (December, 2022). Namely, Firefox has yet to implement it, while Node.js has only started supporting it since version 16.0.0.
|
||||
Reference in New Issue
Block a user