I have a helper function to replace params in a string with the params provided –
type FormatStringParameter = string | number;
/**
* Temporary function to replace params in a string with the params provided
*
* @param input The string that has params i.e. {0}, {1}...
* @param params An array of strings representing the params
*/
export function formatString(input: string, ...params: FormatStringParameter[]): string {
if (params && params.length) {
for (let i = 0; i < params.length; ++i) {
input = input && input.replace(`{${i}}`, params[i] as string);
}
}
return input;
}
The string variables are:
const str = "Hello World! {0}"
const linkText = "Click Here!"
How can I use the formatString
function to display the text = Hello World! Click Here!
with ‘Click Here!’ being a link (not plain text)
I tried const outputText = formatString(str, linkText);
but since the formatString
function only takes string as input, I am getting an error.
2
Answers
That is not so easy.
The hardest part would be to split the string
input
into a list of strings and links, and probably to determine if an individualparam
should be a link or a normal text.formatString
needs to export a DOM node, or an array of DOM nodes, instead of a string.But also the code that calls
formatString
needs to be able to handle DOM nodes, so only fixingformatString
is not enough.A quick (incomplete) example of creating DOM links:
For the sake of completeness: React also lets you write HTML code directly into an element (including links), but that is dangerous and you should not do it. That’s why it’s called ‘dangerouslySetInnerHTML’.
Two observations :
params
array is a link or plain text ?link
URL given ?If you have all the elements as a link in the
params
array, Then you can simply replace them with HTML<a>
tag inside replace function itself.