Newer
Older
libxmljs-extra / src / utils.js
@dreptin dreptin on 28 Apr 2021 892 bytes Initial commit
/**
 * Adds the namespace prefix before every node name in a given path.
 * @param {string} namespacePrefix The alias to give to the namespace.
 * @param {string} xpath The XPath to add the prefix in.
 * @example addNamespacePrefixInPath('tei', '/TEI/text/body'); // returns '/tei:TEI/tei:text/tei:body/tei:p'
 */
function addNamespacePrefixInPath(namespacePrefix, xpath) {
  let fullPath = '';

  for (let i = 0; i < xpath.length; i++) {
    fullPath += xpath[i];

    if (xpath[i] === '/' && xpath[i + 1] !== '/') fullPath += `${namespacePrefix}:`;
  }

  return fullPath;
}

/**
 * Checks if a URL is valid.
 * @param {string} url The URL to check.
 */
function isValidURL(url) {
  try {
    // eslint-disable-next-line no-unused-vars
    const _url = new URL(url);
  } catch (err) {
    return false;
  }

  return true;
}

module.exports = {
  addNamespacePrefixInPath,
  isValidURL,
};