【问题标题】:js replace regex first letter to uppercase [duplicate]js将正则表达式的第一个字母替换为大写[重复]
【发布时间】:2018-04-16 15:02:37
【问题描述】:

我有这样的 XML 内容

<abc:content><bcd:position>Just text: node not need to replace</abc:content>

我需要将其替换为

<abc:Content><bcd:Position>Just text: node not need to replace</abc:Content>

在 SublimeText 或 Notepad++ 中,如果我搜索,我可以用正则表达式替换它

:. or :\b(\w) or :\b.

替换成

:\U$1

它工作正常。但是我不能用

string.replace(/:\b./g , ':\U$1');

这不能正常工作!如果我尝试使用 ':$1'.toUpperCase() 它仍然没有给出正确的结果 - 这用于其他问题,并且不适合我。 请帮帮我!

【问题讨论】:

标签: javascript regex replace


【解决方案1】:

您可以使用替换功能:

var xml = '<abc:content><bcd:position></abc:content>';

var xml2 = xml.replace(/:\w/g, function(matched) {
  return matched.toUpperCase();
});

console.log(xml2);

请记住,在这里使用正则表达式并不是一个好主意,因为它还会替换您的 XML 中冒号之后的任何其他字母:

var xml = '<abc:content><bcd:position>Just text:node not need to replace</bcd:position></abc:content>';

var xml2 = xml.replace(/:\w/g, function(matched) {
  return matched.toUpperCase();
});

console.log(xml2);

【讨论】:

  • 它非常接近,但我不需要替换文本节点。但现在我认为我可以忍受它。我将使用 match '/b' 而不是 /w
  • @AlexLatro 是的,我特别指出这是使用正则表达式的问题。有更好的方法来转换 XML(例如 XSLT)。
【解决方案2】:

您可以使用函数回调进行替换,如下所示:

var js = '<abc:content><bcd:position></abc:content>';
js.replace(/:(\w)/g, function(c) { return c.toUpperCase() });
//"<abc:Content><bcd:Position></abc:Content>"

【讨论】:

    【解决方案3】:

    var str = "<abc:content><bcd:position></abc:content>";
    var div = document.createElement('div');
    div.innerHTML = "Source: " + str.replace(/\</g, '&lt').replace(/\>/g, '&gt');
    document.body.appendChild(div);
    str = str.replace(/:(\b)./g , function(x){return x.toUpperCase();});
    div = document.createElement('div');
    div.innerHTML = "Result: " + str.replace(/\</g, '&lt').replace(/\>/g, '&gt');
    document.body.appendChild(div);

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 1970-01-01
      • 2019-09-07
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多