Home > OS >  JavaScript how replace function gets the value from spread syntax?
JavaScript how replace function gets the value from spread syntax?

Time:01-12

I have the following React code,

const useDynamicReplaceVariable = ({ label, formikValues, fieldsTypes }) => {
  const { locale } = useTranslationState();

  const formattedLabel = useMemo(() => {
    const variablesRegex = /\?([\w-] )\?/g;
    let labelResult = label;
    
    if (variablesRegex.test(label)) {
      labelResult = ' ';
      if (Object.keys(formikValues).length > 0) {
        labelResult = label.replace(variablesRegex, (_, ...[variable]) => {
          const type = fieldsTypes[variable];
          // Set undefined or null to empty
          let variableValue = (formikValues[variable] === undefined || formikValues[variable] == null) ? '' : formikValues[variable];
          if (variableValue && [DesignerDdTypes.DatePicker, DesignerDdTypes.DatetimePicker].includes(type)) {
            variableValue = dateToString(variableValue, locale, type === DesignerDdTypes.DatetimePicker);
          }
          return variableValue;
        });
      }
    }
    return labelResult;
    // eslint-disable-next-line react-hooks/exhaustive-deps  
  }, [label, JSON.stringify(formikValues)]);

  return { formattedLabel };
};

I can't understand the line labelResult = label.replace(variablesRegex, (_, ...[variable]), when no variable is defined, how come spread syntax is applied over it?

CodePudding user response:

...[variable] is a shorthand for

function someFunction(...args) {
  const [variable] = args
}

someFunction(1, 2, 3, 4, 5)

function someFunction(arg1, ...args) {
  console.log('arg1', arg1)
  console.log('args', args)
  const [variable] = args
  console.log('variable', variable)
}

someFunction(1, 2, 3, 4, 5)

function someFunction(arg1, ...[variable]) {
  console.log('arg1', arg1)
  console.log('variable', variable)
}

  • Related