Removing quotation marks from JSON encoded string [closed] - javascript

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 currently have a JSON encoded string generated by inputting values from a array, it is as follows -
"["{value: 97049}","{value: 84866}","{value: 39402}","{value: 30250}","{value: 33363}"]"
I need to convert it to the following format :
"[{value: 97049},{value: 84866},{value: 39402},{value: 30250},{value: 33363}]"
Thanks.

$input = $json_var;
$input = str_replace( '"', '', $input ); // strip em
$input = '"' . $input . '"'; // wrap back around

JS:
var json_array = JSON.parse(json_string);
for (var i = 0; i < json_array.length; i++) {
json_array[i] = JSON.parse(json_array[i];
}
PHP:
$json_array = json_decode($json_string);
$json_array = array_map('json_decode', $json_array);
It would probably be better to fix this at the source. If it's supposed to be an array of objects, don't quote each array element before adding them to the array.

var myQuotedJson = '"["{value: 97049}","{value: 84866}","{value: 39402}","{value: 30250}","{value: 33363}"]"';
var myUnquotedJson = myQuotedJson.replace(/"/, '');

You can do that like this:
var input = '"["{value: 97049}","{value: 84866}","{value: 39402}","{value: 30250}","{value: 33363}"]"';
output = '"' + input.replace('"','') + '"';
//Alerts your output
alert(output );

Related

replace the string from just before the last dot(.) [closed]

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 3 years ago.
Improve this question
I have a string like A/B/C/D.txt
So I want to replace the character just before the last . with the new one.
Like I would add E in last So the output should be A/B/C/E.txt
Can this is possible with only replace and concat Or Regex should help?
I'm sure the output is correct.
A/B/C/E.txt
var filename = 'A/B/C/D.txt';
var dotIndex = filename.lastIndexOf('.');
document.write(filename.substr(0, dotIndex-1) + 'E'+filename.substr(dotIndex, filename.length-dotIndex));
var parts = 'A/B/C/D.txt'.split('.');
if(parts.length > 1)
{
parts[parts.length-2] = parts[parts.length-2].replace(/.$/,"E");
let result = parts.join('.');
console.log(result);
}
Try this:
let name = "A/B/C/D.txt"
let res = name.substr(0, name.lastIndexOf(".")) + "E." + name.substr(name.lastIndexOf(".") + 1);
console.log(res);

Coloring the same elements in a string [closed]

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 3 years ago.
Improve this question
I work with JavaScript on my bachelor thesis.
I would like to read a string and mark the elements that are the same and follow each other in the same color.
I have not found a good approach yet.
I would be grateful for a good proposal.
This is what i have right now.
function colorsetting(input){
var collength = input.length;
var now = '', last2 = '', colored = '';
now = last2 = input[0];
for(var i = 1; i <= collength, i++){
if(now !== last2){
colored = last2.fontcolor("green");
last2 = now;
}
now = input[i];
}
colored = last2.fontcolor("red");
return colored;
}
You can split up your input string using a regex:
/(.)\1*/g
(.) grabs any character, and stores that in capture group 1.
\1* then tells the regex to match as many of those as it can.
Then, iterate over that array, wrap the strings in a span, each with their own colour.
const str = "aaaabbbb123aaaaccccz";
const result = str.match(/(.)\1*/g);
console.log(result);
result.forEach(t => {
// Create a span element
const span = document.createElement("span");
// Set the text in that span to be the current match
span.innerText = t;
// Set the span's color to something random.
span.style.color = "#"+((1<<24)*Math.random()|0).toString(16);
document.body.append(span);
})
(random color code from here)

How to validate postcode in a form using JavaScript [closed]

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 7 years ago.
Improve this question
I'm trying to validate a postcode using JavaScript.
I have my regex.
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$
This is my function so far, not sure how to implement regex.
function validatePostcode()
{
var postcode = document.getElementById("postcode").value;
}
Any other suggestions that would format a postcode that matches;
CF24 9DG
You can do something like this:
function validatePostalCode(){
var regExp = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/;
var postcode = document.getElementById("postcode").value;
if( regExp.test( postcode ) ){
// Do something here, result is true.
} else {
alert("result is false");
}
}
You can try it out in this fiddle: http://jsfiddle.net/Cedriking/5b8wtf1f/2/
You should use JavaScript test() Method RegExpObject.test(string) that returns:
TRUE if the input string matches the RegExpObject regex
FALSE if the input string does not match the RegExpObject regex
Your validator function should look like this:
var validatePostCode = function(postCode) {
var parsePostCode = 'your_regex';
return parsePostCode.test(postCode);
};
var postCode = document.getElementById("postcode").value;
validatePostCode(postCode); // calling the validator function

JavaScript: Unexpected token [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Introduce the problem before you post any code:
I have a simple JavaScript code and it's giving me an unexpected token error. It's code that I'm trying to convert from PHP to JavaScript for use in a Phonegap application.
Specifically it is the line that declares the $ex_data variable. And it says the unexpected token is the section between the $system and $galaxy variables.
Code
for ($galaxy = 1; $galaxy < 21; $galaxy++){
for ($system = 1; $system < 601; $system++){
var $ex_data = '{"planet_id":-1,"sid":'.$system.',"language":"en","gid":'.$galaxy.'}';
var $url = "http://54.193.106.113/ING004/android1/WebServer/Web/sogame/newControl/nmUniverse/getUniverse?sign=".toUpperCase($sign);
}
}
CLEAR QUESTION:
How do I fix the line so that it is valid?
You are confusing PHP concatenation with JavaScript (C) concatenation.
for ($galaxy = 1; $galaxy < 21; $galaxy++) {
for ($system = 1; $system < 601; $system++) {
var $ex_data = '{"planet_id":-1,"sid":'
. $system . ',"language":"en","gid":' . $galaxy.'}';
var $url = "http://54.193.106.113/ING004/android1/WebServer/Web/sogame/newControl/nmUniverse/getUniverse?sign="
.toUpperCase($sign);
}
}
Change the ".s" to "+s".
var $ex_data = '{"planet_id":-1,"sid":'
+ $system + ',"language":"en","gid":' + $galaxy + '}';
or alternatively
var $ex_data = JSON.stringify({
"planet_id" : -1,
"sid" : $system,
"language" :"en",
"gid" : $galaxy
});
Also, as pointed out below, change .toUpperCase($sign); -> + $sign.toUpperCase();
var $ex_data = '{"planet_id":-1,"sid":' + $system + ',"language":"en","gid":' + $galaxy +'}';
var $url = "http://54.193.106.113/ING004/android1/WebServer/Web/sogame/newControl/nmUniverse/getUniverse?sign=" + $sign.toUpperCase();

I can't replace this pattern in javascript [closed]

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 8 years ago.
Improve this question
I need your help on my new project
I hate regular expressions and its rules but i must use it this project.
want do this replace
var aString = '[bkz:sample key]';
I want get into key variable 'sample key' value from this aString
var key,clean;
key = 'sample key';
clean = cleanChars(key);
// clean = sample_key
//my target
key
how can i do this?
thanks in advance
function extractKey(str) {
var match = (str || '').match(/^\[bkz:(.+)\]$/);
return match? match[1] : '';
}
extractKey('[bkz:sample key]'); //sample key
var aString = "[bkz:sample key]";
var regex = /^\[(.+)\:(.+)\]$/;
var matches = regex.exec(aString);
// "sample key" should now be in matches[2]

Categories