<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Kürklü Digital Engineering]]></title><description><![CDATA[Practical engineering notes from Kürklü Digital on web tools, URL handling, analytics, and business workflows. We share reproducible examples and the trade-offs]]></description><link>https://kurkludigital.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 11:38:14 GMT</lastBuildDate><atom:link href="https://kurkludigital.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Counting Turkish phrases in JavaScript]]></title><description><![CDATA[Build a JavaScript phrase counter with Turkish casing, Unicode normalization, overlapping matches and an explicit denominator.]]></description><link>https://kurkludigital.hashnode.dev/counting-turkish-phrases-in-javascript</link><guid isPermaLink="true">https://kurkludigital.hashnode.dev/counting-turkish-phrases-in-javascript</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Kürklü Digital]]></dc:creator><pubDate>Tue, 06 Oct 2026 20:01:21 GMT</pubDate><content:encoded><![CDATA[<p>A phrase counter can return an exact-looking percentage while leaving its most important assumption unstated. Does a two-word phrase use the number of words as its denominator, or the number of places where that phrase could start?</p>
<p>This tutorial builds a small, explicit counter for space-separated text. It handles Turkish casing, normalizes equivalent Unicode representations and counts overlapping phrases. The example is intentionally small enough to inspect and run locally.</p>
<h2>Define what one result means</h2>
<p>For a text containing N tokens and a target containing k tokens, there are max(0, N − k + 1) possible starting positions. We will divide the number of matches by that value.</p>
<p>Consider “rapor rapor rapor”. There are three words, but only two positions for “rapor rapor”. Both positions match. Our function reports two matches out of two positions, or 100%. A tool dividing by total words would report 66.67%. Neither output explains itself without the denominator.</p>
<p>Expose the match count and the number of positions alongside the percentage. Do not label the result an SEO score.</p>
<h2>Normalize and tokenize deliberately</h2>
<p>Turkish distinguishes dotted and dotless I. In the Turkish locale, “I” becomes “ı” and “İ” becomes “i”. The locale must be a chosen input, not an accidental machine default. JavaScript's locale-aware lowercasing supports this distinction; see the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase">MDN reference</a>.</p>
<p>NFC normalization makes canonically equivalent character sequences comparable. For example, an e followed by a combining acute accent and a precomposed é can normalize to the same representation. It does not translate, remove accents or perform stemming. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize">normalization reference</a> explains those forms.</p>
<pre><code class="language-javascript">function tokens(text, locale = 'tr-TR') {
  return text.normalize('NFC').toLocaleLowerCase(locale)
    .match(/[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu) ?? [];
}

function phraseFrequency(text, phrase, locale = 'tr-TR') {
  const words = tokens(text, locale);
  const target = tokens(phrase, locale);
  if (!target.length) throw new Error('Enter a non-empty phrase');
  const positions = Math.max(0, words.length - target.length + 1);
  let count = 0;
  for (let start = 0; start &lt; positions; start++) {
    if (target.every((word, offset) =&gt; words[start + offset] === word)) count++;
  }
  return { count, positions, percent: positions ? count / positions * 100 : 0 };
}
</code></pre>
<p>The loop advances one token after every comparison, including after a match. That is what makes overlapping matches possible. A target longer than the text has zero available positions. Empty text returns zero matches; an empty target is an input error.</p>
<h2>Test the assumptions, not just a happy path</h2>
<p>Run the following with the functions above in a modern Node.js ES module:</p>
<pre><code class="language-javascript">import assert from 'node:assert/strict';

assert.deepEqual(tokens('I İ ı i'), ['ı', 'i', 'ı', 'i']);
assert.deepEqual(tokens('cafe\u0301 café'), ['café', 'café']);
assert.deepEqual(phraseFrequency('rapor rapor rapor', 'rapor rapor'),
  { count: 2, positions: 2, percent: 100 });
assert.equal(phraseFrequency('rapor', 'rapor hazırla').positions, 0);
assert.equal(phraseFrequency('', 'rapor').percent, 0);
assert.throws(() =&gt; phraseFrequency('rapor', '...'), /non-empty/);
</code></pre>
<p>These are reproducible examples, not measurements of a customer project. Keep rounding in the presentation layer so subsequent calculations can use the original result.</p>
<h2>Make the limits visible in the interface</h2>
<p>This tokenizer is a deliberate simplification for our examples, not a universal language processor. Punctuation becomes a separator, so a phrase can cross a sentence boundary. “Bitti. Yeni” produces the tokens “bitti” and “yeni”. If your application requires sentence-local phrases, segment sentences first and count positions within each sentence.</p>
<p>The regex also does not retain every possible combining mark, identify word boundaries in all writing systems, or equate straight and curly apostrophes. Choose and test a different segmentation policy when your audience requires it. Do not advertise support for every language on the strength of a Unicode regex.</p>
<p>Finally, “rapor”, “raporu” and “raporlar” remain separate tokens. A frequency count cannot tell whether a passage explains a topic well. Use it to locate repetition, then read the sentences.</p>
<p>For a browser-based comparison, our <a href="https://kurkludigital.com/araclar/anahtar-kelime-yogunlugu?utm_source=hashnode&amp;utm_medium=referral&amp;utm_campaign=phrase_counter_20261006">Turkish keyword frequency tool</a> displays counts and phrase frequencies with this position-based interpretation. The functions in this article remain usable independently of the tool.</p>
]]></content:encoded></item><item><title><![CDATA[Build UTM URLs without breaking the destination]]></title><description><![CDATA[Build a JavaScript UTM URL helper that preserves query values and fragments, replaces stale tags, and handles Unicode with URLSearchParams.]]></description><link>https://kurkludigital.hashnode.dev/build-utm-urls-without-breaking-the-destination</link><guid isPermaLink="true">https://kurkludigital.hashnode.dev/build-utm-urls-without-breaking-the-destination</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Kürklü Digital]]></dc:creator><pubDate>Thu, 24 Sep 2026 21:43:12 GMT</pubDate><content:encoded><![CDATA[<p><strong>AI disclosure:</strong> This tutorial and its original code examples were prepared with AI assistance.</p>
<p>A campaign link can already contain a language selector, repeated filters, or a fragment pointing to a section. Appending a string such as <code>?utm_source=email</code> can lose the distinction between those components. Reusing an old campaign link can also retain yesterday's creative label.</p>
<p>This example treats campaign tagging as a deliberate transformation: parse the destination, validate the new fields, replace the previous campaign, and return the resulting URL. It runs without fetching the destination or installing a package.</p>
<h2>Define the replacement policy first</h2>
<p>For this tutorial, the caller supplies <code>source</code>, <code>medium</code>, and <code>campaign</code>; all three must contain text. Google recommends including these fields when adding campaign parameters. Campaign values are case-sensitive, so naming consistency matters. <a href="https://support.google.com/analytics/answer/10917952?hl=en">Google Analytics campaign URL guidance</a></p>
<p>The example trims surrounding whitespace but keeps capitalization and Turkish characters. If a team wants lowercase identifiers, that should be a separate, documented naming policy applied to campaign fields. Never lowercase the destination string: <code>/Docs/Guide</code>, query values, and fragments may carry meaningful case.</p>
<p>Optional <code>term</code> and <code>content</code> values can be omitted. This implementation owns the whole <code>utm_</code> namespace: every old UTM field is removed before the new campaign is added. Other query fields stay in order, including repeated keys.</p>
<h2>Implement the transformation</h2>
<p>Save this as <code>utm-example.mjs</code>. The <code>URL</code> API provides the parsed protocol, credentials, path, query, and fragment. Its constructor also rejects inputs it cannot parse without a base URL. <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">MDN: URL</a></p>
<pre><code class="language-javascript">export function buildCampaignUrl(destination, tags) {
  if (typeof destination !== 'string') {
    throw new TypeError('Destination must be a URL string.');
  }
  const url = new URL(destination.trim());
  if (url.protocol !== 'https:' &amp;&amp; url.protocol !== 'http:') {
    throw new TypeError('Only HTTP and HTTPS destinations are supported.');
  }
  if (url.username || url.password) {
    throw new TypeError('Credentials are not allowed in campaign URLs.');
  }
  if (!tags || typeof tags !== 'object' || Array.isArray(tags)) {
    throw new TypeError('Campaign fields must be an object.');
  }

  const required = ['source', 'medium', 'campaign'];
  const fields = [...required, 'term', 'content'];
  const replacements = [];

  for (const field of fields) {
    const value = tags[field] === undefined ? '' : tags[field];
    if (typeof value !== 'string') {
      throw new TypeError(field + ' must be a string.');
    }
    const cleaned = value.trim();
    if (required.includes(field) &amp;&amp; !cleaned) {
      throw new TypeError(field + ' is required.');
    }
    if (cleaned) replacements.push(['utm_' + field, cleaned]);
  }

  // Snapshot keys before deleting: deleting while iterating can skip entries.
  for (const key of [...url.searchParams.keys()]) {
    if (key.toLowerCase().startsWith('utm_')) {
      url.searchParams.delete(key);
    }
  }
  for (const [key, value] of replacements) {
    url.searchParams.set(key, value);
  }
  return url.toString();
}
</code></pre>
<p>Only key classification uses <code>toLowerCase()</code>. This is our cleanup policy for spellings such as <code>UTM_SOURCE</code>; it does not mean every analytics system treats differently cased parameter names as equivalent.</p>
<p>The snapshot of keys makes deletion predictable. Removing entries while walking a live parameter iterator can skip later entries. Collecting replacement values first also ensures that missing fields produce an error before serialization.</p>
<h2>Make stale values impossible to overlook</h2>
<p>Suppose an old link contains two <code>utm_source</code> entries, an old <code>utm_content</code>, and <code>utm_id=42</code>. Updating only source and campaign would leave part of the old campaign attached.</p>
<p>Here, omitted optional fields mean “remove,” not “keep.” Extra UTM fields such as <code>utm_id</code> and <code>utm_source_platform</code> are also deliberately cleared. This five-field teaching example is unsuitable for workflows that require those fields until its accepted inputs are extended. Show that replacement behavior in any user interface rather than silently surprising its operator.</p>
<h2>Pass characters as values</h2>
<p>Use plain values such as <code>İlkbahar &amp; Yaz</code> and <code>C++</code>. Do not pre-encode them or interpolate them into a query string. <code>URLSearchParams</code> handles encoding when individual values are set; a literal plus sign becomes <code>%2B</code>, while a space can serialize as <code>+</code>. <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams">MDN: URLSearchParams</a></p>
<p>Preservation here means decoded query values. Serialization can change <code>%20</code> to <code>+</code> or encode <code>~</code>. An existing unescaped plus is already interpreted as a space, so the builder cannot recover an intended literal plus. Avoid rewriting signed URLs or destinations that depend on the exact query bytes.</p>
<h2>Test outcomes the reader can inspect</h2>
<p>Save this compact suite beside the implementation as <code>utm-example.test.mjs</code>:</p>
<pre><code class="language-javascript">import test from 'node:test';
import assert from 'node:assert/strict';
import { buildCampaignUrl } from './utm-example.mjs';

const fields = {
  source: 'newsletter',
  medium: 'email',
  campaign: 'İlkbahar &amp; Yaz',
};

test('preserves destination and replaces old campaign', () =&gt; {
  const result = new URL(buildCampaignUrl(
    'https://example.com/Docs?tag=A&amp;tag=B'
      + '&amp;utm_source=old&amp;utm_source=older&amp;utm_content=stale#StepOne',
    { ...fields, term: 'C++' },
  ));
  assert.equal(result.pathname, '/Docs');
  assert.equal(result.hash, '#StepOne');
  assert.deepEqual(result.searchParams.getAll('tag'), ['A', 'B']);
  assert.deepEqual(result.searchParams.getAll('utm_source'), ['newsletter']);
  assert.equal(result.searchParams.has('utm_content'), false);
  assert.equal(result.searchParams.get('utm_campaign'), 'İlkbahar &amp; Yaz');
  assert.equal(result.searchParams.get('utm_term'), 'C++');
});

test('rejects inputs outside the contract', () =&gt; {
  assert.throws(() =&gt; buildCampaignUrl('ftp://example.com/', fields));
  assert.throws(() =&gt; buildCampaignUrl('https://u:p@example.com/', fields));
  assert.throws(() =&gt; buildCampaignUrl('https://example.com/',
    { ...fields, campaign: '   ' }));
});
</code></pre>
<p>Run <code>node --test utm-example.test.mjs</code> from that directory. A useful larger suite should independently vary each required field, reject non-string values, and check uppercase UTM keys, both HTTP schemes, and optional blanks. Also apply the same campaign twice: the second result should equal the first rather than accumulate tags.</p>
<p>These checks answer whether the URL transformation follows its contract. They do not verify that the destination exists, that redirects retain the query, or that an analytics installation records a visit. Before sharing a real campaign, open its final destination and verify the resulting campaign fields in the actual measurement setup. The URL builder's responsibility ends at a predictable, inspectable URL.</p>
]]></content:encoded></item></channel></rss>