How to remove all matches?

-1

var b = "Holaa Holaa Holaa Holaa ";
console.log(b);

How can I remove all Holaa matches except the first?

Exactly I mean the whole chain itself, taking into account this example:

String.prototype.repetir = function(v) {
  
  return v < 1 ? '' : new Array(v+1).join(this);
  
};

var b = "hola pepe !".repetir(4);

console.log(b);

Basically, how to do the recursive form of the repeat function, eliminating all the coincidences of the whole sentence, not just words, but as if we did not know that there is that repeat function.

    
asked by Eduardo Sebastian 04.07.2017 в 11:46
source

4 answers

2

var texto = "Holaa Holaa Holaa Adios Pedro Holaa";
var res = texto.split(" ");

arr = res.filter( function( item, index, inputArray ) {
           return inputArray.indexOf(item) == index;
    });

alert(arr);

First pass it to an array ( .split() ), and then filter it ( .filter() )

var texto = "Holaa Holaa Holaa";
var res = texto.split(" ");

arr = res.filter( function( item, index, inputArray ) {
           return inputArray.indexOf(item) == index;
    });

alert(arr);
    
answered by 04.07.2017 в 11:56
0

Good, try this:

s = 'Holaa Holaa Holaa Holaa ';
s = s.replace(/(?!^)Holaa/g, '');
alert(s);
    
answered by 04.07.2017 в 11:52
0

With this you can easily solve it and add to the set only one occurrence of each of the words that come out in your chain.

With the split you separate the string by spaces in an array and you add the elements to a Set, which has the property that the elements do not repeat themselves in it.

var b = "Holaa Holaa Holaa Holaa";
let mySet = new Set();
var array = b.split(" ");
for(let item of array){
  mySet.add(item);
}
    
answered by 04.07.2017 в 12:10
0

I understand that what you're looking for is a method that looks at whether a string is a repetition of another smaller string and, in that case, extract this one:

String.prototype.repetir = function(v) {  
  return v < 1 ? '' : new Array(v+1).join(this);
};

String.prototype.deshacerRepetir = function(){
  var re = /^(.+?)+$/;
  var match = re.exec(this);
  return match[match.length-1];
}

var b = "hola pepe !".repetir(4);

console.log(b.deshacerRepetir());
    
answered by 04.07.2017 в 12:44