首页 > 解决方案 > 从 Strig 中删除 "," (并返回 RGB\n 字符串)

问题描述

所以我已经被这个问题困扰了几天:我的输入是这样的:

"255,255,255,10,251,91,31,4,220,220,220,1"

它是一个具有 3 个不同 RGB 值的字符串,它还带有一个数字,表示它们的数量从最高到最低。您可以将上面的字符串翻译为:

"RED1, GREEN1, BLUE1, QUANTITY1, RED2, GREEN2 ... "

1 代表第一种颜色,2 代表第二种,依此类推。

我需要返回的是没有数量的第一种颜色。所以我的输出应该是这样的:

"255,255,255,251,91,31,220,220,220"

我尝试了很多东西,一个是这个功能:

var firstC, secondC, thirdC;
var pointer = "firstC";

function getEachColorValue(color) {
    var startIndex = 0;
    var endIndex = 0;

    for (var i = 0; i < color.length; i++) {

        if (color.charAt(i) == ",") {
        endIndex = i;

            if (pointer == "firstC") {
                firstC = color.substring(startIndex, endIndex);
                startIndex = endIndex + 1;
                pointer = "secondC";
            } else if (pointer == "secondC") {
                secondC = color.substring(startIndex, endIndex);
                startIndex = endIndex + 1;
                pointer = "thirdC";
            } else if (pointer == "thirdC") {
                thirdC = color.substring(startIndex, endIndex);
                startIndex = endIndex;
                pointer = "firstC";
            }
        }
    }
}

这推动RED1firstC, GREEN1insecondCBLUE1inthirdC

我曾经想过这样做,使用一个函数将 firstC,secondC,thirdC 写入数组,重置它们。然后切割成col3没有第一个调色板的子串,然后重复。

// Global variables
var stringHolder;
var newString;
var counter = 0;
var colorSetHT = new Array;

// main
createSubstring(col3);

function createSubstring(color) {
    var startIndex = 0;
    var endIndex = 0;

    for (var i = 0; i < color.length; i++) {
        if (color.charAt(i) == ",") {
            counter++;
            endIndex = i;
    }
    if (counter == 4) {
        stringHolder = color.substring(startIndex, endIndex);
        alert(stringHolder);
        newString = color.substring(endIndex+1, color.length);

        getEachColorValue(stringHolder);
        colorSetHT.push(firstC, secondC, thirdC)
        colorReset();

        counter = 0;
        stringHolder = "";
//          createSubstring(newString); // ?
        }
    }
}

我试过这个,但到目前为止没有运气。我什至尝试递归地做到这一点。我对 Javascript 有点陌生(实际上是为 Extendscript 做的),我认为有一种更简单的方法,可以使用,split/slice但我还没有找到。我试图让它尽可能简单和快速地阅读,如果我能提供任何进一步的信息,请告诉我,提前谢谢!

标签: javascriptsubstringrgbcolor-pickerextendscript

解决方案


以下是如何使用split.

var input = "255,255,255,10,251,91,31,4,220,220,220,1";
var inputArray = input.split(",");
var outputArray = [];
for(let i = 0;i<inputArray.length;i++)
{
  if(i%4 != 3)
  {
    outputArray.push(inputArray[i]);
  }
}
var output = outputArray.join(",");
console.log(output);


推荐阅读