4

I'm currently learning Angular I'm having an issue with transforming a certain long string.

So, this is my div with a lot of lines, generated by ng-repeat:

http://pastebin.com/raw/bJqqUvpY

Yeah, it's pretty nasty, I know. What i want to do is to remove all the ng attributes and other stuff that I don't need from that string, because I'm going to pass this data to PHP via ajax.

Here's what I tried to do (angular):

    $scope.updateHtml = function() {    
    var testVal = angular.element('#sendHtml').val();
        testVal = testVal.replace(/ng-class="{'selected':selection.indexOf($index) != -1}"/g,"");
    $scope.sendHtml.html = testVal;
};

But it doesn't work. Perhaps it's because of the quotation marks inside of the phrase, or is it?

This, for instance, works with a replacement of a single letter:

$scope.updateHtml = function() {
     var testVal = angular.element('#sendHtml').val();
     testVal = 'abcabcabc';
    testVal = testVal.replace(/b/g,"");
    $scope.sendHtml.html = testVal;
};

Then $scope.sendHtml.html is equal to 'acacac' like it should. Could this be solved with another kind of RegEx?

halfer
  • 19,824
  • 17
  • 99
  • 186
vane41
  • 378
  • 1
  • 2
  • 6
  • The `$` is a special regex char, it must be escaped. Dot, `(`, and `)` should be escaped, too. See http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript – Wiktor Stribiżew Nov 22 '16 at 18:44
  • Thank you for your help! Much appreciated! – vane41 Nov 22 '16 at 19:17

2 Answers2

3

Escape dot ., parenthesis (), and dollar $ signs.

testVal = testVal.replace(/ng-class="{'selected':selection\.indexOf\(\$index\) != -1}"/g,"");

Demo: http://regexr.com/3enmj

On the website you can examine all characters that should be escaped, by opening menu Reference - Escaped Characters.

Community
  • 1
  • 1
Evgeniy Maynagashev
  • 690
  • 1
  • 8
  • 13
1

If you need to remove all the ng-* directives as well as the html comments generated you can try the following regex.

\sng-[a-z]*="(.*?)"|(<!--(.*?)-->)

You remove a whitespace \s followed by ng- and any number of characters [a-z]* followed by double quotes and what's inside "(.*?)" as well as the html comments <!--(.*?)--> and what's inside.

Can probably be improved but it works for cleaning your input.

gyc
  • 4,300
  • 5
  • 32
  • 54