xMatthew41x xMatthew41x - 14 days ago 7
AngularJS Question

Removing specific phrases from a long string (replace function + regex?) in AngularJS

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? I hope I managed to explain my problem clearly. I'd be grateful for any kind of help!

Cheers!

Answer

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.