Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

Convert quotation marks for Portable Text

By Espen Hovlandsdal

Script to convert quotation marks in Portable Text blocks

convertQuotationMarks.js

const defaults = {open: '«', close: '»', find: '"'}

module.exports = function convertQuotationMarks(blocks, chars = defaults) {
  const characters = chars === defaults ? defaults : Object.assign({}, defaults, chars)
  const find = characters.find.replace(/([?!${}*:()|=^[\]/\\.+])/g, '\\$1')
  const pattern = new RegExp(find, 'g')

  return blocks.map(block => {
    if (block._type !== 'block' || !block.children) {
      return block
    }

    let isOpen = false
    const children = block.children.map(child => {
      if (child._type !== 'span' || !child.text) {
        return child
      }

      const text = child.text.replace(pattern, () => {
        const char = isOpen ? characters.close : characters.open
        isOpen = !isOpen
        return char
      })

      return Object.assign({}, child, {text})
    })

    return Object.assign({}, block, {children})
  })
}

This script convert quotation marks in top-level Portable Text blocks. Define open and closing quotation marks and the character you want to change from in the defaults object.

Contributor

Other schemas by author

Auto-reload Studio when changes are deployed

Drop this into your Studio to let editors know when there's a more recent version of your Studio available, making sure they have the latest fields and validations.

Go to Auto-reload Studio when changes are deployed