字符串拆分为javascript对象

时间:2016-02-16 09:17:55

标签: javascript object split

我有来自服务器的字符串:

//A
123|155-244
  • 第一个数字总是表示'红色'
  • |之后的数字始终表示'绿色'
  • -之后的数字始终表示'蓝色'

这里的问题是Green和Blue可以按任意顺序返回:

//B
123-244|155

或者他们可能完全失踪:

//C
123|155 

我需要一个函数来返回一个数组/对象以简化操作:

//A
var result = {red:"123", green:"155", blue:"244"}

//B
var result = {red:"123", green:"155", blue:"244"}

//C
var result = {red:"123", green:"155", blue:"0"}

我尝试过两个函数,一个是Green,另一个是Blue,但是我意识到它不能正常运行,具体取决于它们出现在字符串中的顺序。

var getGreen = function(myvar){
    return myvar.split('-'); 
};
var getBlue = function(myvar){
    return myvar.split('|'); 
};

这样做有时会导致我的对象看起来像这样:

var result = {red:"123", green:"155", blue:"244|155"}

我该怎么办?

8 个答案:

答案 0 :(得分:17)

不需要正则表达式:

parse = function(s) {
    return {
        red:   parseInt('+' + s, 10) || 0,
        green: parseInt(s.split('|')[1], 10) || 0,
        blue:  parseInt(s.split('-')[1], 10) || 0,
    };
};

//

test = [
    '123',
    '222|333-444',
    '55-66|77',
    '123|456',
    '123-456',
    '|123-456',
    '-123|456',
    '010|020-030',
  
];
  
test.map(parse).forEach(r => 
   document.write('<pre>' + JSON.stringify(r) + '</pre>'));

这使用parseInt在第一个非可解析字符处停止并在给定垃圾时返回虚假值的事实。 '+' + s hack是使前导破折号无效(否则会被误认为减号)。

答案 1 :(得分:10)

你最好使用Regexp来匹配这个 - 一个字符串的每一部分。

exec()每个正则表达式和匹配项将存储在结果数组的索引1中。如果没有匹配项,则null会返回exec(),因此请使用[null, 0]的虚拟数组来简化操作。

虽然不是必需的,但如果没有红色值,这也有效。

function getRGB() {
  var reRed = /^([0-9]+)/; // start of string (^) then match 1+ numbers
  var reGreen = /\|([0-9]+)/; // a "|" then match 1+ numbers
  var reBlue = /-([0-9]+)/;  // a "-" then match 1+ numbers

  return {
    red: (reRed.exec(input) || [null, 0])[1],
    green: (reGreen.exec(input) || [null, 0])[1],
    blue: (reBlue.exec(input) || [null, 0])[1]
  };
}

// RGB
var input = '123|155-244';
console.log(input, getRGB(input));

// RBG
var input = '123-244|155';
console.log(input, getRGB(input));

// RB
input = '123-244';
console.log(input, getRGB(input));

// BG
var input = '-244|155';
console.log(input, getRGB(input));

答案 2 :(得分:5)

您可以将String#match与RegEx一起使用。

&#13;
&#13;
var str = '123|155-244';

var result = {
    red: (str.match(/^\d+/) || [0])[0], // Get first digits or zero
    green: (str.match(/\|(\d+)/) || [0, 0])[1], // Get digits after `|` or zero
    blue: (str.match(/-(\d+)/) || [0, 0])[1] // Get digits after `-` or zero
};

console.log(result);
document.getElementById('pre').innerHTML = JSON.stringify(result, 0, 4);
&#13;
<pre id="pre"></pre>
&#13;
&#13;
&#13;

原始回答

误解为-|是可以互换的,但颜色序列将固定为红色,绿色,然后是蓝色。

您可以将String#split与正则表达式一起使用。

&#13;
&#13;
var str = '123|155-244';
var colors = ['red', 'green', 'blue'];
var result = {};

var arr = str.split(/\||-/g);
arr.forEach((e, i) => result[colors[i]] = arr[i]);

console.log(result);
document.getElementById('result').innerHTML = JSON.stringify(result, 0, 4);
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13;

正则表达式说明:

简单的正则表达式\||-将按管道|-拆分字符串。

另一个现场演示:

&#13;
&#13;
var colors = ['red', 'green', 'blue'];

document.getElementById('input').addEventListener('keyup', function() {
  var str = this.value;
  var result = {};

  var arr = str.split(/\||-/g);
  arr.forEach((e, i) => result[colors[i]] = arr[i]);
  console.log(result);
  document.getElementById('result').innerHTML = JSON.stringify(result, 0, 4);
}, false);
&#13;
<input id="input" />

<pre id="result"></pre>
&#13;
&#13;
&#13;

答案 3 :(得分:3)

你说第一个数字总是红色所以

myString = "123-155|244";
red = "0";
green = "0";
blue = "0";
red = mysString.substring(0,3);
if(myString.indexOf("|")!=-1)
{
  green = mystring.substring(myString.indexOf("|")+1,myString.indexOf("|")+4);
}
if(myString.indexOf("-")!=-1)
{
  blue = mystring.substring(myString.indexOf("-")+1,myString.indexOf("-")+4);
}
console.log(red+green+blue);

答案 4 :(得分:2)

您可以使用string.match(regex)

&#13;
&#13;
var str = "123|155-244",  // <--------the string
  arr = str.match(/(\d{3})+/g), // <----creates array out of str
  obj = {
    red: arr[0], // put first one as red value
    green: arr[1], // second one as green value
    blue: arr.length == 3 ? arr[2] : "000" // as per length of array put blue value 
  };

document.querySelector('pre').innerHTML = JSON.stringify(obj);
&#13;
<pre></pre>
&#13;
&#13;
&#13;

答案 5 :(得分:2)

可能这就是你想要的,并根据你的需要写一些其他条件

var color = {red:null,blue:null,green:null};
var s ="123-244|155";
var blue_index = s.indexOf("|") ;
var green_index = s.indexOf("-") ;
if(blue_index>green_index){
    color.blue = s.split("|")[1];
    s = s.split("|")[0];
}else{
    color.green = s.split("-")[1];
    s = s.split("|")[0];
}
if(s.indexOf("|") > -1){
    color.blue =  s.split("|")[1];
    color.red  =   s.split("|")[0];
}   
if(s.indexOf("-") > -1){
    color.green =  s.split("-")[1];
    color.red  =   s.split("-")[0];
}

答案 6 :(得分:2)

你可以试试这个,最后尝试用所有3个条件进行测试 -

    var obj =[{"id":"6dq1oht32tdp66i9s2bd9a21lk@group.calendar.google.com","title":null,"events":[{"start":{"date":null,"time":"2016-02-16T10:00:00+01:00"},"end":{"date":null,"time":"2016-02-16T11:00:00+01:00"},"location":"Kreuzberg, Berlin, Germany","description":"Basketball Test","color_id":"1","ical_uid":"a5fq8vu8gur943bucj5ajr2mb4@google.com"},{"start":{"date":null,"time":"2016-02-15T20:00:00+01:00"},"end":{"date":null,"time":"2016-02-15T21:00:00+01:00"},"location":"Prenzlauer Berg, Berlin, Germany","description":"Football test","color_id":"9","ical_uid":"od9404scajlnskmsc8t32peljk@google.com"},{"start":{"date":null,"time":"2016-02-17T09:00:00+01:00"},"end":{"date":null,"time":"2016-02-17T10:00:00+01:00"},"location":"Neuk\u00f6lln, Berlin, Germany","description":"Baseball Test","color_id":"7","ical_uid":"jtek50q1pche91gl5q1i1pk028@google.com"},{"start":{"date":null,"time":"2016-02-18T10:00:00+01:00"},"end":{"date":null,"time":"2016-02-18T11:00:00+01:00"},"location":"Baseball Test","description":"Baseball Test","color_id":"2","ical_uid":"71l2cak9b7jvp1fmpuc68fshg8@google.com"},{"start":{"date":null,"time":"2016-02-16T20:00:00+01:00"},"end":{"date":null,"time":"2016-02-16T21:00:00+01:00"},"location":"Somewhere","description":"Elsewhere","color_id":"2","ical_uid":"d6d20ep8tvlo594eeinhv02170@google.com"},{"start":{"date":null,"time":"2016-02-13T08:00:00+01:00"},"end":{"date":null,"time":"2016-02-13T09:00:00+01:00"},"location":"Prenzlauer Berg, Berlin, Germany","description":"YEAH! Football!","color_id":"1","ical_uid":"qm3vrnd73eqnls2lsurm9hmc3s@google.com"},{"start":{"date":null,"time":"2016-02-15T09:00:00+01:00"},"end":{"date":null,"time":"2016-02-15T10:00:00+01:00"},"location":"Neuk\u00f6lln, Berlin, Germany","description":"test name","color_id":"2","ical_uid":"7t4l93vnkfedhaeuk3vkaqmssg@google.com"}]}];
    var converted = [];
    $.each(obj[0].events,function(i,eItem){
     formatted = moment(eItem.start.time);

                converted.push({

                    date: formatted.format('YYYY-MM-DD'),

                    formatted_date: formatted.format('DD.MM.YY'),
                    formatted_time: formatted.format('HH:mm') + ' Uhr',

                    location: eItem.location,
                    description: eItem.description,
                    link: eItem.ical_uid,
                    category: eItem.color_id == null ? 'default' : eItem.color_id

                });

    });
 console.log(converted);

答案 7 :(得分:-1)

请尝试此代码 HTML: -

<h1 id="red">Red</h1>
<h1 id="green">Green</h1>
<h1 id="blue">Blue</h1>
<input type="submit" id="byBtn" value="Change" onclick="change()"/>

JavaScript的: -

 var myvar="123-244|155";
 var getGreen = myvar.split('-');
var getBlue = getGreen[1].split('|');
function change(){
red.innerHTML+=" ="+getGreen[0];
blue.innerHTML+=" ="+getBlue[0];
green.innerHTML+=" ="+getBlue[1];
}