antonyboom antonyboom - 1 month ago 20
Javascript Question

regex camelize particular text inside string

I have a next string:

$scope.string = "User {{User Firstname}} </p><p>System {{Reported System Name}} </p><p>Desc {{Description}}</p><ol></ol>"


I'm trying to achieve next result:

$scope.string = "User {{userFirstname}} </p><p>System {{reportedSystemName}} </p><p>Desc {{description}}</p><ol></ol>"


With help of regex I can find necessary for camelize text

if ($scope.string.match(/\{\{(.*?)\}\}/g)){
for (var i = 0; i < $scope.string.match(/\{\{(.*?)\}\}/g).length; i ++){
$scope.string.match(/\{\{(.*?)\}\}/g)[i] = camelizeBrackets($scope.string.match(/\{\{(.*?)\}\}/g)[i])
}
}


But the function
camelizeBrackets
which I have found here and modified to work with text inside curly braces doesn't work at all

function camelizeBrackets(str) {
return str.replace(/\{\{(?:^\w|[A-Z]|\b\w|\s+)\}\}/g, function(match, index) {
if (+match === 0) return "";
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}


Could anybody explain me what I'm doing wrong?

My plunker

sln sln
Answer Source

You could do it in 2 steps, get the inner brackets contents, then camelize that.

(Note - you can replace the not-word \W with a whitespace \s if you only
want to delete whitespace)

Explained

    ^ \W* 
    ( \w )                        # (1), First letter of first word
 |                          # or,
    \b 
    ( \w )                        # (2), First letter of other words
 |                          # or,  
    ( \W )                        # (3), Non-words, whitespace, etc...

function camelize(str)
{
   return str.replace( /^\W*(\w)|\b(\w)|(\W)/g,
      function(match, g1,g2,g3) {
          if ( g1 != null )    // first word, first letter
             return g1.toLowerCase();
          else
          if ( g2 != null )    // second word's, first letter
             return g2.toUpperCase();

          return '';           // all non-word letters( wsp )
      }
   )
}

function camelizeBrackets(str)
{
   return str.replace(/\{\{([\S\s]*?)\}\}/g,
      function(match, g1) {
         return '{{' + camelize( g1 ) + '}}';
        }
      );
} 

console.log( camelizeBrackets("{{EquipmentClass name}}") );
console.log( camelizeBrackets("{{Equipment className}}") );
console.log( camelizeBrackets("{{equipment class name}}") );
console.log( camelizeBrackets("{{Equipment Class Name}}") );

console.log( camelizeBrackets("User {{User Firstname}} </p><p>System {{Reported System Name}} </p><p>Desc {{Description}}</p><ol></ol>") );

All output {{equipmentClassName}}

with
User {{userFirstname}} </p><p>System {{reportedSystemName}} </p><p>Desc {{description}}</p><ol></ol>
at the end.