decodeVars
API Reference for the decodeVars() string function
Overview
Since declareVar adds ICU-compatible markers to source text, it can create issues for any existing string-processing logic.
The decodeVars function extracts original values from strings that contain declareVar markers.
function getGreeting({ name }) {
const greeting = "Hello, " + declareVar(name);
// "Hello, {_gt_, select, other {Brian}}"
const decodedGreeting = decodeVars(greeting);
// "Hello, Brian" <- the string as if `declareVar` was never used
return decodedGreeting;
}Because declareVar only affects encoded strings, it is only meant for use with source strings and has no effects on translated strings.
String Processing:
Use decodeVars when you need to process strings that contain declareVar markers with existing string manipulation logic.
Reference
Parameters
| Name | Type | Description |
|---|---|---|
icuString | string | A string containing ICU markers from declareVar calls. |
Returns
A string with ICU markers removed, containing the original variable values.
Example
Basic Usage
Extract original values from strings with variable markers.
import { declareVar, decodeVars } from 'gt-next';
const encodedVar = declareVar(name);
// "{_gt_, select, other {Alice}}"
const decodedVar = decodeVars(encodedVar);
// "Alice"Multiple Variables
decodeVars can be used with multiple variables.
import { declareVar, decodeVars } from 'gt-next';
const name1 = "Alice";
const name2 = "Bob";
const encodedVar = "Hello, " + declareVar(name1) + "! My name is " + declareVar(name2);
// "Hello, {_gt_, select, other {Alice}}! My name is {_gt_, select, other {Bob}}"
const decodedVar = decodeVars(encodedVar);
// "Hello, Alice! My name is Bob"Notes
- Only use
decodeVarswhen you need to process strings containingdeclareVarmarkers - The function specifically targets ICU MessageFormat patterns created by
declareVar - Original variable values are preserved exactly as they were before encoding
- Does not affect translation processing - only removes markers for string manipulation
- decodeVars is not a general ICU MessageFormat parser and should not be used on arbitrary ICU strings
Next steps
- See
declareVarfor marking dynamic content - See
declareStaticfor creating static function calls - See
msgfor string encoding and decoding patterns
How is this guide?