Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - Count string occurrence and replace with string and count - JS

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...