Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a string like
"Something has happened {\"prop1\":{\"name\":\"foo\"}}"
and I would like to parse out the JSON so that I can format the string. Such as:
Something has happened
{
"prop1":{
"name":"foo"
}
}
In JavaScript, what would be a good way to accomplish this.
There can be multiple object in the string and also the object will not be known it could contain many nested objects or arrays. Thanks in advance.
The minimum would be simply pretty-printing the string
OK then. Well a really simple, non-optimised, not-necessarily robust pretty print function might look something like this:
function basicPrettyPrint(str) {
var output = '';
var indentLevel = 0;
var indent = ' ';
var inQuotes = false;
for (var i = 0; i < str.length; i++) {
var current = str[i];
if (current === '"' && indentLevel > 0) {
inQuotes = !inQuotes;
output += current;
} else if (inQuotes) {
output += current;
} else if (current === ',' && indentLevel > 0) {
output += ',\n' + indent.repeat(indentLevel);
} else if (current === '{' || current === '[') {
if (indentLevel === 0) output += '\n';
output += current + '\n' + indent.repeat(++indentLevel);
} else if (current === '}' || current === ']') {
output += '\n' + indent.repeat(--indentLevel) + current;
if (indentLevel === 0) output += '\n';
} else {
output += current;
}
if (indentLevel < 0) {
// parse failure: unbalanced brackets. Do something.
}
}
return output;
}
var input = 'Here is a "simple" object, for testing: {"prop1":{"name":"foo"}}And here is a more complicated one that has curly brackets within one of the property values:{"prop1":"{this is data, not an object}","arr":[1,{"a":"1","b":{"x":1,"y":[3,2,1]}},3,4]}And a non-nested array:[1,2,3]';
console.log(basicPrettyPrint(input));
The above doesn't allow for escaped quotation marks within properties, and probably a bunch of other things I didn't think of for purposes of a quick demo, but I leave those things as exercises for the reader...
P.S. The string .repeat() method might need to be polyfilled.
Can we assume that the '{' and '}' indicate the start and end of the json. If so, you can get a substring; see code below. You could do the same thing with regular expressions.
var str = "Something has happened {\"prop1\":{\"name\":\"foo\"}}"
var start = str.indexOf("{");
var end = str.lastIndexOf("}");
var json = str.substr(start, end);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i have an array and i want to insert "ZZ" if the current array value(string) contains "ata", the code should replace at the end of "ata" word.
var duplicatesArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"
];
var uniqueArray = duplicatesArray.filter(function(elem, pos) {
return duplicatesArray.indexOf(elem) == pos;
});
for (var i = 0; i < uniqueArray.length; i++) {
var st = uniqueArray[i];
if((st.endsWith("mak")==false) && (st.endsWith("mek")== false) && (st.length>3))
{
var b = "ata";
var insert = "ZZ";
var position = st.indexOf("b");
st = st.slice(0, position) + insert + st.slice(position);
document.writeln(st);
document.write("<br>");
}
}
I may need to edit this answer later once some details have been clarified, but it seems like you should use the .map() method on your uniqueArray.
This code will walk through each word in the list and either let it unchanged or apply the replacement if all conditions are fulfilled.
// using a shorter, already deduplicated list for sake of clarity
var uniqueArray = [
"abıca","gelmek","ata","atabeg","at","eri","yir","atalar","tutmak"
];
var result = uniqueArray.map(function(word) {
return (
!word.endsWith("mak") &&
!word.endsWith("mek") &&
word.length > 3 ?
word.replace(/ata/, "ataZZ") : word
);
});
console.log(result);
I am right or wrong? :)
var initialArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"];
var newArray = []
var regexp = /(ata)(.*)?/;
for (var i = 0; i< initialArray.length; i += 1) {
newArray.push(initialArray[i].replace(regexp, "$1ZZ$2"))
}
console.log(newArray)
// ... "gelmek", "ataZZ", "ataZZbeg" ...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am creating one function in javaScript:
function myFunction() {
var str = "1,12,3,4";
if (str.contains("1,12,4,3")) {
alert("yes");
} else {
alert("No");
}
}
o/p: NO..i want the o/p as "Yes " because all elements are there.
I think you want to compare the comma separated elements contained in the string, not the string itself.
So you can use split and sort to build and sort your arrays and an "equality function" to check them.
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You can try use a sorting/comaring function:
var str = "1,12,3,4";
var str2 = "1,12,4,3";
var myArray1 = str.split(",");
var myArray2 = str2.split(",");
alert(arraysEqual(myArray1, myArray2))
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
a.sort();
b.sort();
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
Demo: http://jsfiddle.net/IrvinDominin/ZT4M8/
String "1,12,3,4" really doesn't contain substring "1,12,4,3". You're shuffling arrays and strings methods. You should convert your string to array (e.g. using split() method), then possible order and after all match.
try this
function myFunction() {
var str = "1,12,3,4";
var str_to_match = "1,12,4,3";
var res = str.split(",");
var res_to_match = str_to_match.split(",");
var flag=1;
for(var i=0; i<res_to_match.length; i++)
{
if(!res.contains(res_to_match[i]))
{
flag=0;
break;
}
}
if (flag==1) {
alert("yes");
} else {
alert("No");
}
}
I think, what you are looking for are the functions split, join and sort:
var myArray = str.split(","); // creates an array with your numbers
myArray.sort(); // sorts the array
var sortedStr = myArray.join(","); // creates a comma separated string of the sorted array
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to count the number of elements (numbers only) in an array using a switch statement in the function. I honestly don't know exactly what this code would look like. But this is what I have so far
<script language="JavaScript">
//an array of numbers
var number = [1,"o",2,3,"a",0];
//a switch statement
switch (number) {
//Not sure what would go here....
break;
}
//display result of count
alert(count)
</SCRIPT>
using a switch statement
if you insist:
var count = 0;
for( var i=0 ; i<number.length ; ++i )
switch( typeof(number[i]) ) {
case "number": ++count; break;
}
count has value 4.
Note: NaN, Number.NEGATIVE_INFINITY, and Number.POSITIVE_INFINITY are also "number"s, so if you don't want to count these then do
var count = 0;
for( var i=0 ; i<number.length ; ++i )
switch( typeof number[i] ) {
case "number":
if( !isNaN(number[i]) && isFinite(number[i]) )
++count;
}
I think the current answers are not very compact.
Here is my take, using .reduce:
var number = [1,"o",2,3,"a",0];
var count = number.reduce(function(accum,cur){
return accum+(typeof cur === "number");
});
Here is a take using the required switch
var number = [1,"o",2,3,"a",0];
var count = number.reduce(function(accum,cur){
return accum+(typeof cur === "number");
switch(true){} // this switch's name is Alfred, after Batman's butler
});
var a = [1,"o",2,3,"a",0];
var nums = 0;
for(var i = 0;i<a.length;i++){
if(typeof a[i] == "number") nums++;
}
alert(nums);
Edit: Okay! A switch! Let's do it!
var count = 0;
for(var i = number.length; i--;){
switch(true){
case typeof number[i] == 'number':
count++;
}
}
alert(count);