简体   繁体   English

计数字符串出现并替换为字符串和计数 - JS

[英]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.我不在乎字符串 'Name' 是否出现不止一次。

Example:例子:

String is 'Name transfer transfer transfer transfertranfser' should return 'Name transfer 5' as 5 is the length of transfer.字符串是 'Name transfer transfer transfer transfertranfser' 应该返回 'Name transfer 5',因为 5 是传输的长度。 String is 'Name transfer Transfer transfer TransferTranfser' should return 'Name transfer 5' as 5 is the length of transfer.字符串是 'Name transfer Transfer transfer TransferTranfser' 应该返回 'Name transfer 5',因为 5 是传输的长度。 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.任何帮助表示赞赏。

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.注意替换正则表达式中的g标志,否则 Javascript 将只替换第一次出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM