首页 > 解决方案 > 从字符串中获取变量

问题描述

我想从一个字符串中获取多个变量。让我们假设字符串是"rgb(74, 29, 87)". 如何从字符串中获取 R、G 和 B 值?

有什么办法可以做一些简单的事情,比如:

const str = rgb(74, 29, 87);
const color = str.grab("rgb({R}, {G}, {B})");

console.log(color);
// Outputs: { R: 74, G: 29, B: 87 }

或者至少在数组而不是对象中获取变量?

标签: javascriptstringvariables

解决方案


没有内置的,但您应该能够基于模式字符串构建正则表达式并将输入与它匹配:

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function grab(str, pattern) {
    let re = escapeRegExp(pattern).replace(/\\{(\w+)\\}/g, ($0, $1) =>
        '(?<' + $1 + '>.+?)'
    )
    return (str.match(re) || {}).groups;
}

const str = 'rgb(74, 29, 87)'
const color = grab(str, "rgb({R}, {G}, {B})");

console.log(color);
// Outputs: { R: 74, G: 29, B: 87 }

(假设一个支持命名捕获组的引擎)


推荐阅读