Are there no better ways to surround a string with a HTML tag (or brackets, or quotation marks, or whitespace) than mundane concatenation?
Inbefore “stupid question”
Very similar problems are notable enough to deserve own API functions:
- Range.surroundContents() (doing exactly that, but only for selections)
- String methods: trim() (doing the opposite for white spaces), split/join(), anchor/link()
- deprecated String methods: big(), blink(), bold(), fixed(), fontcolor(), fontsize(), italics(), small(), strike(), sub/sup()
Edit: Such questions are clearly not stupid for creators of Javascript.
Who is more likely stupid: creators of Javascript or you?
Use cases
I wish I could write something like:
div.innerHTML = rawstr.split("\n\n").join("", "<p>", "</p>");
newstr = oldstr.split(/\s+“|”\s+/g).join(" ", "\"", "\"");
var str = "Joan – despite her curly hair – is loved.";
return str.split(/\s+–/s+/g).join(" ", "(", ")");
var str = "Joan (despite her curly hair) is loved.";
return str.split(/\s+\(|\)/s+/g).join(" – ");
← Oh, wait... I can already do this one.
...instead of:
div.innerHTML = rawstr.split("\n\n").map(str => "<p>" + str + "</p>")).join("");
newstr = oldstr.split(/\s+“|”\s+/g).map(str => "\"" + str + "\"")).join(" ");
- a)
var str = "Joan – despite her curly hair – is loved.";
b)
var p = str.split(/\s+–/s+/g);
return p[0] + " " + "(" + p[1] + ")" + " " + p[2];var str = "Joan – despite her curly hair – is loved.";
var p = str.split(/\s+–/s+/g);
p[1] = "(" + p[1] + ")";
return p.join(" "); - –
When I can do this, my life will be complete.
')`?
– Dan D. Apr 14 '17 at 13:33