2016-07-06 70 views
-5

我的问题是下一个:如何解析字符串并将其存储在不同的变量[Javascript]中?

我有一个特殊字符的字符串,在不同部分“分隔”字符串。

var str = "this could be part 1 -- this is part 2 -- here is part3"; 

在这里,我选择' - '作为特殊的字符组来划分零件。 我会从这个字符串希望能够分离这些部件,并把每一个数组中,并得到这样的结果:

this could be part 1 , this is part 2 , here is part3 

有什么更好的方式来做到这一点?

预先感谢您的回答

+1

您是否尝试过的东西?我建议做一些研究,比如[split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)函数的功能 –

回答

1

另一个答案是恕我直言,太复杂了这一点。

在这里我希望它更容易太明白:

// watch out for spaces, it's a usual mistake 
var str = "this could be part 1 -- this is part 2 -- here is part3"; 

/* this extracts the parts between the ' -- ' and 
puts them in an indexed array starting from 0 */ 
var result = str.split(" -- "); 

,如果你想吐出他们中的一个使用它像这样:

alert(result[0]); // first index returns 'this could be part 1' 

check demo

1

VAR individualValues = str.split( “ - ”);

+2

这个答案如果你添加一些解释,它会如何帮助OP,会更好。事实上,由于其简洁,它可能会进入“低质量”审核队列。 –

+0

谢谢,我在这里找到更多解释:http://www.w3schools.com/jsref/jsref_split.asp – saperlipopette

0

.split()只是返回一个数组,因此您可以使用它轻松地分配新变量。我将沿着这些行创建一个函数。

function parse_string(theString) { 
    var stringSplit = theString.split(“ -- "); 

    var stringParts = { 
      first : stringSplit[0], 
      second : stringSplit[1], 
      third : stringSplit[2] 
     }; 
return stringParts; 

}

然后就可以调用它任何时候你需要解析的字符串。

var parsedString = parse_string("this could be part 1 -- this is part 2 -- here is part3 

alert(parsedString.first); // should alert "this could be part 1" 
alert(parsedString.second); // should alert "this is part 2" 
alert(parsedString.third); // should alert "here is part3" 
相关问题