Format the text in JavaScript alert box
Solution 1
You can use only:
\b = Backspace
\f = Form feed
\n = New line
\r = Carriage return
\t = tab
\000 = octal character
\x00 = hexadecimal character
\u0000 = hexadecimal unicode character
So, you can insert different ASCII characters, but not format them (like italic or bold).
EDIT I also have to mention, that in fact alert
acts like toString
conversion, so including tags and/or styles is not possible.
Solution 2
Underline a string using unicode character '\u0332'
, called a COMBINING LOW LINE
function underline(s) {
var arr = s.split('');
s = arr.join('\u0332');
if (s) s = s + '\u0332';
return s;
}
var str = underline('hello world'); // "h̲e̲l̲l̲o̲ ̲w̲o̲r̲l̲d̲"
alert(str);
This method is not guaranteed to produce a smooth underline.
Example of confirm()
on Firefox 59:
Solution 3
You can not style the text inside an alert box. But you can use a modal box solution instead, here's a list to get you started:
- Dialog, from jQuery UI
- Simple Modal
- leanModal
- Reveal: jQuery Modal
Solution 4
In my case I created internationalization through a JavaScript file. I needed a mnemonic on each button so I was looking for an easy solution. Actually, I've an easy approach to get the wanted result:
\u0332
is the Unicode Character COMBINING LOW LINE
With this character you can underline single letters.
Demonstration:
alert('S\u0332earch - s underlined');
i18n = {};
i18n.SEARCH = "S\u0332earch - s underlined";
document.getElementById('search').innerHTML = i18n.SEARCH;
<button id="search"></button>
Solution 5
You can't. Use external lib as JQuery UI Dialog or your own implementation.
praveen
Updated on July 06, 2021Comments
-
praveen almost 3 years
How can I format the text in a JavaScript alert box? I need a word in the text to be underlined.