-1

I have XML content like this

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

and I need replace it with

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

In SublimeText or Notepad++ I can replace it with regex, if I search for

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

and replace it with

:\U$1

It works fine. But I cant use

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

this dont work correctly! If I try use ':$1'.toUpperCase() its still dont give right result - This used in other questions, and dont work for me. Help me, please!

Alex Latro
  • 93
  • 1
  • 10

3 Answers3

2

You can use a replacement function:

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

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

console.log(xml2);

Bear in mind that using regex is not a very good idea here as it will also replace any other letters in your XML that come right after a colon:

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);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Its very close, but i dont need to replace text nodes. But now I thik I can live with it. I will use match '/b' not /w – Alex Latro Nov 03 '17 at 20:02
  • @AlexLatro Yeah, I specifically pointed out that that was a problem with using regex for this. There are better ways to transform XML (XSLT, for example). – JLRishe Nov 03 '17 at 20:03
1

You can use a function callback for the replacement, like so:

var js = '<abc:content><bcd:position></abc:content>';
js.replace(/:(\w)/g, function(c) { return c.toUpperCase() });
//"<abc:Content><bcd:Position></abc:Content>"
dave
  • 62,300
  • 5
  • 72
  • 93
0

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);
Fresh Friend
  • 489
  • 1
  • 3
  • 11