Your regular expression /\\.br<[0-9]+>\\/g
is not correct. In the regex context, the period (.
) means "any character except for line breaks". Therefore, you must escape the dot in your regex pattern.
/\\\.br<[0-9]+>\\/g
/(\\\.br<([0-9]+)>\\)/g
When considering using String.prototype.replace as suggested by T.J. Crowder, a possible solution could be:
function replacer(match, p1, p2, offset, string) {
let result = '';
for (let i = 0; i < Number(p2); i++) {
result += '\n';
}
return result;
}
var newString = String('Hello \\.br<3>\\ World!').replace(/(\\\.br<([0-9]+)>\\)/g, replacer);
console.log(newString);
Keep in mind that the hardcoded string in the code includes two backslashes (\\
) since it is an escape character. However, when getting the string from a user input field, entering just one backslash (\
) is sufficient.