1

I'm trying to clean strings which has been transformed from word text but I'm stuck on removing special character '…'

By click on button "clean", script removes all dots and only one special character, however I need to remove all of them

Where is my mistake?

Here is my code and plunker with struggles

    $scope.string = "My transformed string ………….........…...."

 $scope.removeDots = function () {
        var em = document.getElementsByTagName('em');
        var reg = /\./g;
        var hellip = /…/g

        angular.forEach(em, function (item) {

            if(item.innerText.match(reg)){
                 item.innerText = process(item.innerText)
            } 
            if (item.innerText.match(hellip)){
              item.innerText = item.innerText.replace("…", "")
            }
        });
    };

    function process( str ) {
        return str.replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) {
            return b + c.replace( /\./g, '' );
        });
    }
antonyboom
  • 1,161
  • 2
  • 17
  • 44

3 Answers3

2

There's a few problems here, but they can all be resolved by simply reducing the code to a single regex replace within process that will handle both periods and … entities:

 $scope.removeDots = function () {
        var em = document.getElementsByTagName('em');
        angular.forEach(em, function (item) {
              item.innerText = process(item.innerText)
        });
    };

    function process( str ) {
        return str.replace( /\.|…/g, '');
    }
});

Plunker demo

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

You replace every occurrence of . in process, but only replace … once.

I don't see why don't you just do something like .replace(/(\.|…)/g, ''); the g modifier makes sure every match is replaced.

9000
  • 39,899
  • 9
  • 66
  • 104
1

You can do both replacements by first replacing the occurrences of … with one point (because it might be the only thing you find), and then replacing any sequence of points by one:

function process( str ) {
    return str.replace(/…/g, '.').replace(/\.\.+/g, '.');
}

var test="My transformed string ………….........…....";

console.log(process(test));

One of the reasons your code did not replace everything, is that you used a string as find argument, which will result in one replacement only. By using the regular expression as find argument you can get the effect of the g modifier.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • You're welcome. Make sure you use a solution that will also work when your string is like `test…`, without any other point. You'll want to turn that into `test.` with the point. ;-) – trincot Jan 20 '17 at 22:10