So when I receive a string from backend for e.g. “This is a test from {X}.” I want the user in the frontend have the ability to modify and replace the {X}, only that and nothing else.
<div
v-if="item.isEditing">
<textarea
class="form-control textWrapInput"
:value="editableString(item.name,
item.isEditing).editableValue"
type="text"
@input="updateItemName(item,
$event.target)"
></textarea>
</div>
<div
v-else>
{{ editableString(item.name,
item.isEditing).displayString
}}
</div>
const
editableString
= (value:
any,
isEditing:
boolean)
=> {
let
displayString
=
'';
let
editableValue
=
'';
if (typeof
value
===
'string') {
const
regex
= /{([^{}]+)}/g;
const
matches
=
value.match(regex);
if (matches) {
if (isEditing) {
displayString
=
value.replace(regex,
(match)
=> {
const
variable
=
match.slice(1,
-1);
return
`{${variable}}`;
});
editableValue
=
value.replace(regex,
(match,
variable)
=>
`{${variable}}`);
} else {
displayString
=
value.replace(regex,
(match)
=> {
const
variable
=
match.slice(1,
-1);
return
`{${variable}}`;
});
editableValue
=
value;
}
} else {
displayString
=
value;
editableValue
=
value;
}
} else {
displayString
=
String(value);
editableValue
=
String(value);
}
return {
displayString,
editableValue,
};
};
const
updateItemName
= (item: {
name:
string; },
textareaElement:
any)
=> {
const
newValue
=
textareaElement.value;
// Get the value of the textarea element
const
originalValue
=
item.name;
// Find all variables within curly braces in the original value
const
regex
= /{([^{}]+)}/g;
let
match;
let
updatedName
=
originalValue;
// Iterate over matches and replace each variable
while ((match
=
regex.exec(originalValue))
!==
null) {
const
variable
=
match[0];
// Full match, including curly braces
const
variableValue
=
newValue.substring(match.index,
match.index
+
variable.length);
// Extract variable value from textarea
updatedName
=
updatedName.replace(variable,
variableValue);
// Replace variable in original string
}
item.name
=
updatedName;
};
So far I am able to remove the variable from the {} and save it like that, but when I attempt to add any string to it within the curly brace for e.g.. {06/12/2024} it wouldn’t save anything. It would just save it as {}.