向字符串中的char添加下划线

时间:2015-08-04 07:12:38

标签: javascript extjs

假设我有这个字符串:Transplantation。

如果我想强调第一个字母,即字母'T',我可以这样做:

string text = "Transplantation";
underscoredText = '<span style="text-decoration: underline;">'+text.charAt(0)+'</span>'+text.substring(1, text.length);

如果我想在字母'n'上加下划线,我该怎么办?

我试过的是:

underscoredText = '<span style="text-decoration: underline;">'+text.charAt(3)+'</span>'+text.substring(1, text.length);

但这是完全错误的,因为我只将索引3处的char显示为字符串中的第一个字母,现在文本看起来像这样:nransplantation(并且下划线仍然在forst字母上(在索引处) 0),现在是n而不是T.

缺乏编程经验,我也想知道这是否是一种做我正在尝试做的坏方法。我这样做的原因是因为我想向用户显示哪些键可以用作热键/快捷键

1 个答案:

答案 0 :(得分:3)

如果你在变量中有这个字母,请说:

var hotkey = "n";

...然后您可以使用String#replace插入span

underscoredText = text.replace(hotkey, '<span style="text-decoration: underline;">$&</span>');

替换字符串中的$&表示“放置与此处匹配的文字”。 replace只会替换第一个实例(如上所述,使用字符串作为第一个参数)。

虽然我想重新使用hotkey会同样好:

underscoredText = text.replace(hotkey, '<span style="text-decoration: underline;">' + hotkey + '</span>');
  

我也想知道这是否是一种做我想做的事情的坏方法。

我会使用类而不是内联样式:

underscoredText = text.replace(hotkey, '<span class="hotkey">$&</span>');

另外,网页上带下划线的文字通常表示链接。虽然我不认为在这种情况下会让人感到困惑,但您可以考虑使用粗体或(如果是菜单)明确列出其旁边的键序列。

无偿的现场例子:

var text = "Transplantation";
var hotkey = "n";
var underscoredText = text.replace(hotkey, '<span class="hotkey">$&</span>');
document.body.insertAdjacentHTML("beforeend", underscoredText);
.hotkey {
  text-decoration: underline;
}