You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中拆分含小数与字符的字符串为数值和非数值部分

Split Numeric and Non-Numeric Parts in JavaScript

Great question! Ditching the separator-insertion approach for regex is way cleaner and more efficient here. Regex lets you directly capture the numeric and unit parts in one go without modifying the original string.

Solution Using Regex Capture Groups

Here’s a straightforward implementation that handles integers, floats, and even cases with spaces between the number and unit:

function splitValueAndUnit(str) {
  // Regex to capture numeric part (including decimals) and the rest
  const match = str.match(/^(\d+\.?\d*|\.\d+)\s*(.*)$/);
  if (!match) return null; // Return null if no valid number found
  
  const [, value, unit] = match;
  return {
    value: parseFloat(value), // Convert to number if needed, or keep as string
    unit: unit.trim() // Remove any leftover spaces from the unit
  };
}

// Test cases
console.log(splitValueAndUnit('1234picas')); // { value: 1234, unit: 'picas' }
console.log(splitValueAndUnit('1234 px')); // { value: 1234, unit: 'px' }
console.log(splitValueAndUnit('145.4us')); // { value: 145.4, unit: 'us' }
console.log(splitValueAndUnit('.5ms')); // { value: 0.5, unit: 'ms' } // Bonus edge case

How the Regex Works

Let’s break down /^(\d+\.?\d*|\.\d+)\s*(.*)$/:

  • ^: Start of the string
  • (\d+\.?\d*|\.\d+): Capture group for the numeric part:
    • \d+\.?\d*: Matches integers (like 1234) or floats with digits before the decimal (like 145.4)
    • |\.\d+: Alternative to handle floats that start with a decimal (like .5)
  • \s*: Matches any number of spaces (including zero) between the number and unit
  • (.*): Capture group for the unit part (everything after the numeric part and optional spaces)
  • $: End of the string

Alternative: Keep Values as Strings

If you don’t need to convert the numeric part to a number (e.g., preserving leading zeros), just return the captured string directly:

function splitValueAndUnitAsString(str) {
  const match = str.match(/^(\d+\.?\d*|\.\d+)\s*(.*)$/);
  if (!match) return null;
  
  return {
    value: match[1],
    unit: match[2].trim()
  };
}

console.log(splitValueAndUnitAsString('1234picas')); // { value: '1234', unit: 'picas' }

This approach is far more concise than inserting separators and splitting, and it handles all the cases you mentioned plus some edge ones.

内容的提问来源于stack exchange,提问作者Jose Cabrera Zuniga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:28:01