Transform all escaped chars to its original value - javascript

My backend has json string arrays, but some of the chars are escaped when send the value to frontend, like " é. How can I change all of the escaped chars to its original value? For some reason, I can't use other JS frameworks. The innerHTML seems didn't be supported in all browsers(like firefox).

You can use below snippet to unescape the string
//Snippet#1
var str="é";
var str_esc=escape(str);
document.write("Escaped String: " + str_esc + "<br>")
document.write("Original String: " + unescape(str_esc))
or
//Snippet#2
var str="é";
var enc_str = encodeURI(str);
var dec_str = decodeURI(enc_str);
document.write("Escaped String: " + enc_str + "<br>")
document.write("Original String: " + dec_str)

Related

JavaScript's console.log printing unwanted characters

So basically what I'm trying to do is print a simple string to the screen using the console.log function.
Here's an example :
const fromLabel: string = '["' + "AppExp" + '"]' + '\n' + '["' + "AppExp" + '"]';
And I ultimately wanna print it, so I go:
console.log(fromLabel);
and my output is:
[\"AppExp\"]\n[\"AppExp\"]
So, basically no carriage return and unwanted '\'.
Any idea what could be the problem?
EDIT: Never mind. I was working with objects and to print them I used JSON.stringify.. little did I know I used it on this string as well ..my bad
Backslashes are escaping certain characters in the string. Your string is put together in a weird way—you're mixing "" and ''. Try this:
var str = '["' + 'AppExp' + '"]' + '\n' + '["' + 'AppExp' + '"]'
console.log(str)
try this code with template literals
I omitted the : string to be able to run the snippet but remember to add it!
const fromLabel = `[""AppExp""]
[""AppExp""]`;
console.log(fromLabel);
or in case you do not want duplicate " chars
const fromLabel: string = `["AppExp"]
["AppExp"]`;
I hope it helps! :)

JSON Parse causing 'undefined' json values - Javascript

I have searched far and wide for answers to my problem but I am just not winning, I am hoping someone will be kind enough to offer me some guidance.
My below Javascript code is returning undefined json values:
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}'
var stringified = JSON.stringify(req);
console.log('stringified json ' + stringified);
//json = JSON.parse(JSON.stringify(stringified))
var json = JSON.parse(stringified );
console.log('parsed json ' + json);
//testing different ways of pulling out the data, all undefined
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json[testValue];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
The complication comes in with the backslash in the testValue property.
If I do not stringify the json first, I receive the following error:
SyntaxError: Unexpected token P in JSON at position 143
As soon as I Stringify however, and then parse, the values come back as undefined.
Does anybody perhaps know what I am doing wrong please?
Thanks
If you know that your data will never properly escape backslashes, a quick solution is the following:
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
JSON.parse(req_escaped)
Basically, make your string JSON compliant and then use the usual parsed method.
replacing the backslashes compiles. also you need to add " around testValue when you get it from the json
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\ProgramTest\\"}';
var req_escaped = req.replace(/\\/g, "\\\\") // escape backslashes
var json = JSON.parse(req_escaped);
console.log(json);
var testId = json["testId"];
var ruleId = json.ruleId;
var testValue = json["testValue"];
console.log('testValue ' + testValue);
var rulePassed = Boolean(json[rulePassed]);
njson = '{"testId": "' + testId + '","ruleId": "' + ruleId + '","testValue": "' + testValue + '","rulePassed": ' + rulePassed + '}';
console.log('final json ' + njson);
If you have control over the escaping process, the backslashes path should be escaped as follows:
\\ should be \\\\
The first escape escapes it in the Javascript string literal. The second escape escapes it in the JSON string literal. Credits and more details.
var req = '{"testId":"12345","ruleId":"678910","rulePassed":true,"testValue":"C:\\\\ProgramTest\\\\"}'
console.log(JSON.parse(req))

adding float in jquery

var sssee = "581.30";
var ssser = "1,178.70";
var ssee = sssee.trim().replace(/,/g, "");
var sser = ssser.trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + parseFloat(ssee + sser))
In log i see:
ee 581.30
er 1178.70
total 581.301178
Why is it when adding replace to remove the , messes the computation.
Variables ssee and sser are both strings. When you peform ssee + sser it would return string 581.301178.70 which would be passed to parseFloat function then. When there are two decimal points, only first is taken as correct, that's why parseFloat returns 581.301178.
Check the snippet with correct solution.
var sssee = 581.30;
var ssser = "1178.70";
var ssee = String(sssee).trim().replace(/,/g, "");
var sser = String(ssser).trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + (parseFloat(ssee) + parseFloat(sser)))
You should also wrap ssee and ssser in String object before using trim and replace methods. Without doing that if you provide those variables as floats, instead of strings, your code won't work.
Your problem:
You concatenate two strings ("581.30" + "1,178.70") to one string ("581.301178.70"). Then you parse it to a float (581.301178).
Solution:
You need to parse each one to a float at first. After do your addition (parseFloat(ssee) + parseFloat(sser)).

How to turn a String with square brackets and forward slashes + variables into a regex?

I've tried to get my head around regex, but I still can't get it.
I want to turn the following String + some variables into a regex:
"[url href=" + objectId + "]" + objectId2 + "[/url]"
I tried the following, since I read somewhere that brackets and slashes need to be escaped:
/\[url href=/ + objectId + /\]/ + objectId2 + /\[\/\url\]/g
But that isn't working.
I want to use it to replace the whole expression into HTML wherever it matches in a String.
You are correct that brackets and backslashes need to be escaped in a regular expression, but you can't create a regex by adding together regex literals like your /\[url href=/ + objectId + /\]/ attempt. To build a regex dynamically like that you have to use string concatenation and pass the result to new RegExp(). So as a starting point for your text you'd need this:
new RegExp("\\[url href=" + objectId + "\\]" + objectId2 + "\\[/url\\]")
Note all of the double-backslashes - that's because backslashes need to be escaped in string literals, so "\\[" creates a string containing a single backslash and then a bracket, which is what you want in your regex.
But if you want to extract the matched href and content for use in creating an anchor then you need capturing parentheses:
new RegExp("\\[url href=(" + objectId + ")\\](" + objectId2 + ")\\[/url\\]")
But that's still not enough for your purposes because objectId and objectId2 could (or will, given the first is a url) contain other characters that need to be escaped in a regex too, e.g., .+?(), etc. So here's a function that can escape all of the necessary characters:
function escapeStringForRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
We can't just call that function on the whole thing, because you need unescaped parentheses for your capturing sub matches, so just call it on the two variables:
var urlRegex = new RegExp("\\[url href=("
+ escapeStringForRegex(objectId)
+ ")\\]("
+ escapeStringForRegex(objectId2)
+ ")\\[/url\\]");
Kind of messy, but seems to do the job as you can see here:
function escapeStringForRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function createAnchors(str, objectId, objectId2) {
var urlRegex = new RegExp("\\[url href=(" + escapeStringForRegex(objectId) + ")\\](" + escapeStringForRegex(objectId2) + ")\\[/url\\]", "g");
return str.replace(urlRegex, "<a href='$1'>$2</a>");
}
document.querySelector("button").addEventListener("click", function() {
var str = document.getElementById("input").value;
var objectId = document.getElementById("objectId").value;
var objectId2 = document.getElementById("objectId2").value;
document.getElementById("output").value =
createAnchors(str, objectId, objectId2);
});
textarea { width : 100%; height: 80px; }
Input:<br><textarea id="input">This is just some text that you can edit to try things out. [url href=http://test.com.au?param=1]Test URL[/url]. Thanks.</textarea>
ObjectId:<input id="objectId" value="http://test.com.au?param=1"><br>
ObjectId2:<input id="objectId2" value="Test URL"><br>
<button>Test</button>
<textarea id="output"></textarea>
Note that the above searches only for [url]s in your string that have the particular href and content specified in the objectId and objectId2 variables. If you just want to change all [url]s into anchors regardless of what href and text they contain then use this:
.replace(/\[url href=([^\]]+)\]([^\]]+)\[\/url\]/g, "<a href='$1'>$2</a>")
Demo:
function escapeStringForRegex(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function createAnchors(str) {
return str.replace(/\[url href=([^\]]+)\]([^\]]+)\[\/url\]/g, "<a href='$1'>$2</a>");
}
document.querySelector("button").addEventListener("click", function() {
var str = document.getElementById("input").value;
document.getElementById("output").value = createAnchors(str);
});
textarea { width : 100%; height: 80px; }
Input:<br><textarea id="input">Testing. [url href=http://test.com.au?param=1]Test URL[/url]. Thanks. Another URL: [url href=https://something.com/test?param=1&param2=123]Test URL 2[/url]</textarea>
<button>Test</button>
<textarea id="output"></textarea>
It's like:
var rx = new RegExp('\\[url\\shref='+objectId+'\\]'+objectId2+'\\[\\/url\\]');
new RegExp("[url href=" + objectId + "]" + objectId2 + "[\url]")
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

javascript search string contains ' + '

i would to search a string into another string but i'm facing an issue.
There is my code :
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.search(str));
//it should alert 8 (index of matched strings)
but it alert -1 : so, str wasn't found into reference.
I've found what's the problem is, and it seems to be the " + " character into str, because .search("string+str") seems to evaluate searched string with the regex " + "
Just use string.indexOf(). It takes a literal string instead of converting the string to a RegExp object (like string.search() does):
> reference = "project/+bug/1234";
> str = "+bug/1234";
> console.log(reference.indexOf(str));
8
Try this:
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.indexOf("+bug/1234"));

Categories