简体   繁体   English

正则表达式替换字符串的一部分

[英]Regex to replace a portion of a string

I've a chart which in the Y axis I have some numbers, like 40000000, 7000000, 20000000. 我有一个图表,其中在Y轴上有一些数字,例如40000000、7000000、20000000。

I'd like to use a Regex to replace the last six '0' numbers by 'M' 我想使用正则表达式将后六个数字“ 0”替换为“ M”

Example

40000000 should be 40M
7000000  should be 7M
20000000 should be 20M

If the number is less then 999999, should be replaced by the letter 'K' 如果数字小于999999,则应替换为字母“ K”

4000 should be 4K

Can someone help me with this regex ? 有人可以帮我这个正则表达式吗?

在此处输入图片说明

注意someString必须是字符串,而不是数字。

someString.replace(/0{6}$/, "M").replace(/0{3}$/, "K");

Untested from mobile, but try: 未经手机测试,但尝试:

/0{6}$/

Full code: 完整代码:

'4000000'.replace(/0{6}$/,'M')

Addressing thousands: 应对数千:

'4000000'.replace(/0{6}$/,'M').replace(/0{3}$/,'K')

Working Sample for M M的工作样本

The regex used is /0{6}\\b/g . 使用的正则表达式为/0{6}\\b/g Note that $ is not used to check the end of the string, but a word boundary character \\b is used which makes this work in a wider range of cases in which other suggestions would fail. 请注意, $不会用于检查字符串的结尾,而是会使用单词边界字符\\b ,这会使它在其他建议失败的情况下更有效。

You can very easily derive a similar one yourself for K , leaving that as an exercise for you :) 您可以很容易地自己为K导出一个相似的值,而将其作为练习:)

After you have done that, you can check if your data matches the first regex or not, and replace if it does. 完成此操作后,您可以检查您的数据是否与第一个正则表达式匹配,并进行替换。 If it doesn't, then test for the second regex (for K) and replace if found. 如果不是,则测试第二个正则表达式(对于K),如果发现则替换。

PS The service I used to post the solution (Regex 101) is a very useful service and is a perfect tool for prototyping and learning regex. PS我用来发布解决方案的服务(Regex 101)是一项非常有用的服务,并且是原型和学习regex的理想工具。

http://jsh.zirak.me/2klw //see this only if you still can't figure out how to do it. http://jsh.zirak.me/2klw ///仅当您仍然不知道如何执行此操作时,才可以看到此内容。

This spoiler contains the solution if you can't figure out how to do it 如果您不知道该怎么做,则可以使用此解决方案

Another approach that produces exactly the desired output: 产生所需输出的另一种方法:

function getRepString (rep) {
  rep = rep+''; // coerce to string
  if (rep < 1000) {
    return rep; // return the same number
  }
  if (rep < 10000) { // place a comma between
    return rep.charAt(0) + ',' + rep.substring(1);
  }
  // divide and format
  return (rep/1000).toFixed(rep % 1000 != 0)+'k';
}

I am not taking credit for this answer. 我不相信这个答案。 This answer was by CMS at a duplicate question found here: 答案是CMS的一个重复问题,在这里找到:

How to format numbers similar to Stack Overflow reputation format 如何格式化类似于Stack Overflow信誉格式的数字

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

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