In a large string, some words wrap by {{ }} in three ways:
1. {{some words}}
2. {{#some words}}
3. {{/some words}}
I need a solution that wraps matches in an extra pair of braces, but it should happen just for the first case, and not for the other two. Only {{some words}} should be replaced to {{{some words}}}.
Currently, I have this code:
const text = "text {{#some words}} text {{some words}} text";
const newText = text.replaceAll("{{", "{{{").replaceAll("}}", "}}}");
console.log(newText);
But this does not take the restriction into account, and wrongly adds parentheses around {{#some words}}, which should remain unchanged.
Is there any solution, possibly with a regular expression?
CodePudding user response:
You can use [^#/] to match any character that is not # and / and use that in the overal regular expression:
let text = "{{hello}} {{#hello}} {{/hello}} {{world}} {{#world}} {{/world}}";
let result = text.replace(/\{\{[^#/].*?}}/g, "{$&}");
console.log(result);
.*?matches any character (except newline) in a lazy manner, i.e. it will stop matching when}}is encountered.$&represents the complete matched string
CodePudding user response:
Use this
const replacing = (word) => {
return word.replace(/\{\{([a-zA-Z0-9 ] )\}\}/g, ((a,b) => `{{{${b}}}`))
}
console.log(replacing("{{some Words}}"))
console.log(replacing("{{#some words}}"))
console.log(replacing("{{/some words}}"))
