简体   繁体   English

Javascript 在字符串中的第 3 个字符后剪切字符串

[英]Javascript cut string after 3th character in string

I need to write function that returns 3strings after character ', ' so if there is none or 1 or 2 or 3 to return empty string if ', ' character is found else return 3 strings...i wrote these function but it is very cpu intensive...can be shorter and faster code?我需要编写 function 在字符 ', ' 之后返回 3 个字符串,所以如果没有或 1 或 2 或 3 返回空字符串,如果找到 ', ' 字符,否则返回 3 个字符串......我写了这些 function 但它非常cpu 密集型...可以更短更快的代码吗?

https://jsfiddle.net/1nfyq327/ https://jsfiddle.net/1nfyq327/

    var str = 'AAA BBB CC., DD EE, FF FF, GG GG, HH HH, II II, JJ JJ, GG GG';

    var res = str.substring(0, str.indexOf(', ', str.indexOf(', ', str.indexOf(', ')+1)+1));

    console.log(res);

Result is:结果是:

AAA BBB CC., DD EE, FF FF

Result is fine but i need faster code because it will execute on low power cpu so speed is very cruicial...结果很好,但我需要更快的代码,因为它将在低功耗 cpu 上执行,所以速度非常关键......

In terms of speed there is not that much you can do.就速度而言,您无能为力。
The code you wrote runs in O(n) , which is the best possible time complexity for your problem.您编写的代码在O(n)中运行,这是您问题的最佳时间复杂度。

You can play around with native functions ( split() , substring() ... that are implemented in c++ and therefore will run quickly) to see if one of them is faster, or rewrite it in pure javascript with a for loop.您可以使用本机函数( split()substring() ...在 c++ 中实现,因此运行速度很快)来查看其中一个是否更快,或者使用for循环在纯 javascript 中重写它。 And compare the results.并比较结果。

In your case the best thing you can really do is write a little benchmark testing how fast your solution is and compare that.在您的情况下,您真正能做的最好的事情是编写一个小基准测试您的解决方案的速度并进行比较。 Althought there is high chance that there is something else in your code that runs slowly.尽管您的代码中很有可能还有其他东西运行缓慢。 :) :)

Use split , slice and join :使用splitslicejoin

 var str = 'AAA BBB CC., DD EE, FF FF, GG GG, HH HH, II II, JJ JJ, GG GG'; var result = str.split(',').slice(0,3).join(','); console.log(result);

You could split with a limit of String#split and join the array.您可以使用String#split的限制拆分并加入数组。

 var string = 'AAA BBB CC., DD EE, FF FF, GG GG, HH HH, II II, JJ JJ, GG GG', result = string.split(',', 3).join(',') console.log(result);

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

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