-2

I have a use case where I have a string with the same substring if followed continuously should return the string and count together. If not, it should return the same string. We need to check for only one value here, in the below use case it is 'transfer'. Should be case insensitive. I do not care if the string 'Name' occurs more than once.

Example:

String is 'Name transfer transfer transfer transfertranfser' should return 'Name transfer 5' as 5 is the length of transfer. String is 'Name transfer Transfer transfer TransferTranfser' should return 'Name transfer 5' as 5 is the length of transfer. String is 'Name transfer name transfer' should return 'Name transfer name transfer' as transfer is not continous.

Please advice.

var temp = "Model transfer transfer transfer transfertransfer";
var count = (temp.match(/transfer/g) || []).length;
let abc;
if (count > 1) {
  abc = temp.replace('transfer', `transfer ${count}`)
}
console.log(count);
console.log(abc)

How do I remove the end of the string? Please advice. Any help is appreciated.

arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60

1 Answers1

1

Use this:

var temp = "Model transfer transfer transfer transfertransfer";
var count = (temp.match(/transfer/ig) || []).length;
let abc;
if (count > 1) {
  abc = temp.replace(/[\s]*transfer[\s]*/ig, '').concat(` transfer ${count}`);
}
console.log(count);
console.log(abc)

This way you are replacing all "transfer" string with additional whitespaces. Mind the g flag in the replace regex as otherwise Javascript will only replace the first occurrence.

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122
  • Doesnt work with Model transfer Transfer transfer Transfertransfer. I want to be case insensitive. But works good for case sensitive ones. – arunmmanoharan Sep 14 '20 at 18:40
  • See updated answer. If you want it to be case insensitive, use the `i` flag on your regular expressions. – Johannes Klauß Sep 14 '20 at 18:41
  • Why does this not return the original string for Model Transfer model transfer? It should only check if transfer is followed by a transfer. If transfer is followed by any other word, we should return the original string – arunmmanoharan Sep 14 '20 at 19:25