[shorthand] how to use a line of code to convert a hump style string into a dash style string

Keywords: Javascript


Today, when reading snabbdom (a Virtual DOM Library) about processing element custom attributes, I found the skill of converting hump style strings into dash style strings, so as to remove the attributes corresponding to the actual DOM elements according to the dataset. As for the corresponding rules of the DOM object's dataset and HTML custom attributes, you can read this document: https://developer.mozilla.org...

Discovery code location

File src/modules/dataset.ts

import {VNode, VNodeData} from '../vnode';
import {Module} from './module';

export type Dataset = Record<string, string>;

const CAPS_REGEX = /[A-Z]/g;  //Match uppercase

function updateDataset(oldVnode: VNode, vnode: VNode): void {
  let elm: HTMLElement = vnode.elm as HTMLElement,
    oldDataset = (oldVnode.data as VNodeData).dataset,
    dataset = (vnode.data as VNodeData).dataset,
    key: string;

  if (!oldDataset && !dataset) return;
  if (oldDataset === dataset) return;
  oldDataset = oldDataset || {};
  dataset = dataset || {};
  const d = elm.dataset;

  for (key in oldDataset) {
    if (!dataset[key]) {
      if (d) {
        if (key in d) {
          delete d[key];
      } else {
        elm.removeAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase()); 
  for (key in dataset) {
    if (oldDataset[key] !== dataset[key]) {
      if (d) {
        d[key] = dataset[key];
      } else {
        elm.setAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase(), dataset[key]); 

export const datasetModule = {create: updateDataset, update: updateDataset} as Module;
export default datasetModule;

Code sample


Operation result


Related documents

String.prototype.replace(): https://developer.mozilla.org...

Posted by gmcalp on Wed, 04 Dec 2019 14:17:50 -0800