javascript - 从字符串中获取变量
问题描述
我想从一个字符串中获取多个变量。让我们假设字符串是"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 }
或者至少在数组而不是对象中获取变量?
解决方案
没有内置的,但您应该能够基于模式字符串构建正则表达式并将输入与它匹配:
// 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 }
(假设一个支持命名捕获组的引擎)
推荐阅读
- python - 如何将字符串分解为多个换行符?
- android - 为什么我的内容显示在我的 Appbar 下方?
- c# - Anima2D 在 Unity3D 2019.2.0f 中崩溃
- apache-spark - 从节点未启动或添加到我的 apache spark 集群
- java - MQJE001:IBM 中的完成代码“2”,原因“2033”问题仅用于获取一些消息
- kubernetes - 使用 Kubernetes client-go 如何以编程方式检查 Node 是否“就绪”?
- html - 页眉的边距使“a”标签不可点击
- java - 多次生成报告时Tomcat服务器冻结
- c++ - 句子转换器在存在新行的情况下不起作用
- javascript - 从我的联系页面接收信息需要什么?