Convert a string that looks like an array into an actual array - javascript

If I have str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]" how could I turn that into a array in JavaScript?
An array where each element of the array is an array itself.
Possible?

You can try this rudimentary function I put together for 2D arrays:
function customParse(data){
arr = []
for(var i = 0; i < str.length; i++){
if(str[i] == ','){
if(!isNaN(str[i-1])){
arr.push(',')
arr.push('"')
}else{
if(str[i-1] != "]"){
arr.push('"')
arr.push(',')
arr.push('"')
}else{
arr.push(',')
}
}
}else{
if(str[i] == ']' && str[i-1] != ']'){
arr.push('"')
}
arr.push(str[i])
}
}
return JSON.parse(arr.join(""))
}
str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]"
result = customParse(str)
alert("Raw: "+result);
alert("Stringified: "+JSON.stringify(result));

A little dirty, but will do the trick. the "matches" variable would contain your array of arrays.
var str = "[[1,Warriors,NBA],[2,Kings,NBA],[3,Knicks,NBA]]";
var cleanStr = str.substring(1,str.length-1)
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(cleanStr)) != null)
{
matches.push(match[1].split(","));
}
Additionally, if you have the option, just define the array in javascript.
var list = [[1,'Warriors','NBA'],['2','Kings','NBA'],[3,'Knicks','NBA']];

There are some javascript parsers written in javascript. See this:JavaScript parser in JavaScript, this:https://github.com/mishoo/UglifyJS, this:http://esprima.org/, this:http://marijnhaverbeke.nl/acorn/.

var array = JSON.parse("[" + str + "]");
or you can use .split(), that will also end up with an Array of strings.

Related

if input string is same as the reversed output string, it should display reversed word

I am trying to check if the input string is the same as the reversed output string, and if so, it should display reversed word.
var word = "cel";
var reverseWord = "lec";
for (i=0; i < word.length; i++) {
for (j=0; j < reverseWord.length; j++) {
if (word[i] === reverseWord[j] && word[i+1] === reverseWord[j+1] && word[i+2] === reverseWord[j+2]) {
console.log("reverseWord----->");
}
}
}
If you want to check if a reversed string is the same as another string, simply use below code
var word = "cel";
var reverseWord = "lec";
console.log(word.split("").reverse().join("") === reverseWord);
Without using the reverse method
var word = "cel";
var reverseWord = "lec";
var arr = [];
for(i=word.length-1;i>=0;i--){
arr.push(word[i]);
}
var new_word = arr.join("");
if(new_word === reverseWord){
console.log("true");
}
else{
console.log("false");
}
So you can use an array to push individual characters of the string into it in reverse order using a loop and convert the array back into a string using join() method and do the check. Hope this helps.

Replacing commas with dot and dot with commas

I am trying to replace all dots for comma and commas for dots and was wondering what is the best practice for doing this. If I do it sequentially, then the steps will overwrite each other.
For example:
1,234.56 (after replacing commas) --> 1.234.56 (after replacing dots) --> 1,234,56
Which is obviously not what I want.
One option I guess is splitting on the characters and joining afterwards using the opposite character. Is there an easier/better way to do this?
You could use a callback
"1,234.56".replace(/[.,]/g, function(x) {
return x == ',' ? '.' : ',';
});
FIDDLE
If you're going to replace more than two characters, you could create a convenience function using a map to do the replacements
function swap(str, swaps) {
var reg = new RegExp('['+Object.keys(swaps).join('')+']','g');
return str.replace(reg, function(x) { return swaps[x] });
}
var map = {
'.':',',
',':'.'
}
var result = swap("1,234.56", map); // 1.234,56
FIDDLE
You could do the following:
var str = '1,234.56';
var map = {',':'.','.':','};
str = str.replace(/[,.]/g, function(k) {
return map[k];
});
Working Demo
Do it in stages using placeholder text:
var foo = '1,234.56';
foo = foo
.replace(',', '~comma~')
.replace('.', '~dot~')
.replace('~comma~', '.')
.replace('~dot~', ',')
You could use a for loop. Something like:
var txt = document.getElementById("txt");
var newStr = "";
for (var i = 0; i < txt.innerHTML.length; i++){
var char = txt.innerHTML.charAt(i);
if (char == "."){
char = ",";
}else if (char == ","){
char = ".";
}
newStr += char;
}
txt.innerHTML = newStr;
Here's a fiddle:
http://jsfiddle.net/AyLQt/1/
Have to say though, #adenoeo's answer is way more slick :D
In javascript you can use
var value = '1.000.000,55';
var splitValue = value.split('.');
for (var i = 0; i < splitValue.length; i++) {
var valPart = splitValue[i];
var newValPart = valPart.replace(',', '.');
splitValue[i] = newValPart;
}
var newValue = splitValue.join(',');
console.log(newValue);

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

remove all empty values from url

I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}

How to check first character in string and how to send that string into an array in Jquery?

friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});

Categories