Watch a live product demo 👀 See how Sanity powers richer commerce experiences

Convert quotation marks for Portable Text

By Espen Hovlandsdal

Script to convert quotation marks in Portable Text blocks


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 => {
    if (block._type !== 'block' || !block.children) {
      return block

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

      const text = child.text.replace(pattern, () => {
        const char = isOpen ? characters.close :
        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.


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