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

如何用纯JavaScript/ES15实现带预定义单位的数值输入解析?

Solution for Parsing Numeric Input with Predefined Units

I’ve put together an ES6+ solution that exactly meets your needs—it handles positive/negative decimals, extracts predefined units, and falls back to your default unit if none is provided. Here’s how it works:

Step-by-Step Implementation

First, let’s create a reusable function that takes the input value, allowed units, and default unit as parameters:

// Helper function to escape special regex characters (like %) so they're treated literally
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

function parseInputValue(inputValue, units, defaultUnit) {
  // Build a regex pattern for our allowed units
  const unitPattern = units.map(escapeRegExp).join('|');
  // Regex to capture: optional negative sign, digits, optional decimal + extra digits, optional matching unit
  const regex = new RegExp(`^(-?\\d+\\.?\\d*)(${unitPattern})?$`, 'i');
  
  const match = inputValue.trim().match(regex);
  
  if (!match) {
    // Handle invalid input (adjust this logic based on your error handling needs)
    return { value: null, unit: defaultUnit.toLowerCase() };
  }
  
  const [, numStr, matchedUnit] = match;
  const value = Number(numStr);
  
  // Use matched unit if present, else default; normalize to lowercase for consistency
  const unit = matchedUnit ? matchedUnit.toLowerCase() : defaultUnit.toLowerCase();
  
  return { value, unit };
}

How to Use It

Let’s test it with your example cases to verify:

// Define your units and default unit
const units = ["px", "em", "%"];
const defaultUnit = "px";

// Test various input scenarios
console.log(parseInputValue("150px", units, defaultUnit)); // { value: 150, unit: 'px' }
console.log(parseInputValue("-100.50em", units, defaultUnit)); // { value: -100.5, unit: 'em' }
console.log(parseInputValue("75%", units, defaultUnit)); // { value: 75, unit: '%' }
console.log(parseInputValue("200", units, defaultUnit)); // { value: 200, unit: 'px' }
console.log(parseInputValue("-45.2", units, defaultUnit)); // { value: -45.2, unit: 'px' }
console.log(parseInputValue("300EM", units, defaultUnit)); // { value: 300, unit: 'em' } (case-insensitive)

Key Features Breakdown

  • Dynamic Unit Support: The regex is built directly from your units array, so you can add/remove units without rewriting the core regex logic.
  • Special Character Safety: The escapeRegExp helper ensures units like % (which have special meaning in regex) are handled correctly.
  • Case Insensitivity: The i flag in the regex means inputs like 100PX or -50Em will parse without issues.
  • Fallback Logic: If no unit is provided, the function automatically uses your specified defaultUnit.
  • Clean Numeric Parsing: It correctly converts positive/negative integers and decimals into proper JavaScript Number values.
  • Whitespace Handling: The trim() call takes care of any leading/trailing spaces in the input.

Edge Case Handling

If you need to handle invalid inputs (like non-numeric values or unrecognized units), the function returns null for the value—you can adjust this to throw an error, display a user message, or use a default numeric value depending on your use case.

内容的提问来源于stack exchange,提问作者stackminu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:04:57