My issue is the following:
I have a field with a file path: "\\random.ad.test.stuff.com\folder\level 1\51. level 2\ level 3"
I want to create an array with this information
function myFunction() {
var str = "\\random.ad.test.stuff.com\folder\level 1\51. level 2\level 3";
var array = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "_");
document.getElementById("demo").innerHTML = array;
}
Problem is that \51 the character code for a right parenthesis. So the result is
"_random_ad_test_stuff_comfolder_level 1__. level 2_level 3".
How can I escape the \51 as well as insert a _after .com ?
You can't escape the string after-the-fact. In a string literal, as you said, \51 is ), exactly as though you'd typed ) in the string literal; there is no difference in the resulting string:
console.log("\51" === ")"); // true
You have to escape the characters in the literal:
var str = "\\\\random.ad.test.stuff.com\\folder\\level 1\\51. level 2\\level 3";
// --------^-^-------------------------^-------^--------^------------^
console.log(str);
Note that this is just because you're using a string literal. If you read that string from somewhere, there's no need to escape it at all. Escaping (in this sense) is a string literal thing, not a string thing.
You've said this comes from an XML file, and asked what you have to do to the file to avoid this problem. The answer is: Nothing. Read in the XML file, and when you get those filenames from it, you'll get strings with the correct characters again, escaping is for string literals, but XML isn't a string literal.
Example:
// "Read" the file
var xmlText = document.querySelector("#xml").textContent;
// Parse it
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(xmlText, "application/xml");
// Use its contents; the information you'll get will be valid strings,
// no escaping needed
var entries = oDOM.querySelectorAll("entry");
console.log(entries[0].getAttribute("attr"));
console.log(entries[1].firstChild.nodeValue);
<script id="xml" type="text/xml"><root>
<entry attr="\\random.ad.test.stuff.com\folder\level 1\51. level 2\level 3" />
<entry>\\random.ad.test.stuff.com\folder\level 1\51. level 2\level 3</entry>
</root></script>
In that example, I've shown taking the string from an attribute, or from the body of an element, the two usual ways you put information in XML.
Related
If the string contains only double quotes, it can be solved like below-
var str=`{"name":"javascript"}`;
var jsonObj=JSON.parse(str) //Works
And if string contains only single quotes , it can be solved like below-
var str = "{'result': ['def', 'abc', 'xyz']}";
str = str.replace(/'/g, '"');
var res = JSON.parse(str);
console.log(res.result);
But how do we convert the below string, where there's single quote inside the double quote-
var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} `
This doesn't look like a valid stringified JSON.
var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} `
error should be wrapped in double quotes instead.
var s=`{"error": "No such file or directory: '../FileSystem/3434-5433-124/'"} `
You can verify it using JSON.stringify
JSON.stringify({
error: "No such file or directory: '../FileSystem/3434-5433-124/'"
})
Assuming that you're using a valid JSON. You can now escape the single quotes with a backslash.
var s = `{"error": "No such file or directory: '../FileSystem/3434-5433-124/'"}`
const parsed = JSON.parse(s.replace(/\'/g, "\'"));
console.log(parsed)
If you know that the only issue is that the property names are single quoted rather than the JSON required double quotes you could use regex to replace the single quotes on property names with doubles.
var s=`{'error': "No such file or directory: '../FileSystem/3434-5433-124/'"} `
const regex = /(')(\S*)('):/g
s = s.replace(regex, '"$2":')
const workingJson = JSON.parse(s);
Should do the trick. This will replace single quotes with doubles for any part of your string that has the format of (single quote)(text)(single quote)(colon), this will most likely only be property names but keep in mind that if another part of your string follows this exact format it will also get it's single quotes replaced by doubles.
i want to replace multiple patterns in the same string using regex and javascript.
What i am trying to do?
i have a string for example
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
now i get all the strings with [] using regex
const get_strings_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
so get_strings_in_brackets will have
["[12#fname lname]", "[23#fname1 lname1]"]
now i want these to be replaced with string "<some-tag id="12"/> "<some-tag id="23"/> in the string "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
also this number 12 in this string "<some-tag id="12"/> is got from the string ["[12#fname lname]" before # character.
What i have tried to do?
i have tried to replace for only one string withing brackets meaning for the example below
string ="hello i am [12#fname lname1]"
const extracted_string_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
const get_number_before_at_char =
extracted_string_in_brackets[0].substring(1,
extracted_string_in_brackets[0].indexOf('#'));
const string_to_add_in_tag = `<some-tag
id="${get_number_before_at_char}"/>`;
const final_string = string.replace(extracted_string_in_brackets,
string_to_add_in_tag);
The above code works if i have only one string within square brackets. But how do i do it with multiple strings in brackets and replacing that with tag string that is for example .
Could someone help me solve this. thanks.
Just use a group reference in your replacement:
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
newstr = string.replace(/\[(.+?)#(.+?)\]/g, '<some-tag id="$1"/>')
console.log(newstr)
How do I parse an array of objects if it contains single quote characters?
For example, I have:
$example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
The single quotes seem to break up the array, making parsing impossible.
You can use backticks (``). It will generate the string as it was written, with double "" and single ' quotes.
var str = `{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}`;
console.log(str);
var obj = JSON.parse(str);
console.log(obj.response[0].uid);
It's a json string not an object.
Use JSON.parse(myJsonSting) and you will get objects with the ' taken care of.
Javascript is supposed to ignore single quotes if it is inside double quotes, in your case try adding backslash before the single quote.
To parse at json string to object
var example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
var objExample = JSON.parse(example);
To convert json object to json string
var StrExample = JSON.stringify(objExample);
this is my string,
var str=""{\"checkedRows\":\"[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]\",\"checkedIndex\":\"[0]\"}"";
I'm trying to get substring as below
[{\"SlNo\":\"1\",\"ItemCode\":\"8\",\"ItemDetail\":\"Cassue Nut\",\"Qty\":\"140\",\"Rate\":\"2000\",\"Amount\":280000\"}]
And i'm trying below code to split
var newStr = str.substring(str.lastIndexOf("[") + 1, str.lastIndexOf("]"))
but unable to fetch it.
Firstly note that you have an extra leading and trailing double quote around your JSON string. Secondly the JSON itself is completely malformed. You need to fix the errors it has (extra/mis-matched double quotes mostly) so it looks like this:
'{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}'
Once you've done that you can parse the string to an object, then retrieve the checkedRows property and stringify that again, like this:
var str = '{"checkedRows":[{"SlNo":"1","ItemCode":"8","ItemDetail":"Cassue Nut","Qty":"140","Rate":"2000","Amount":280000}],"checkedIndex":[0]}';
var obj = JSON.parse(str);
var newStr = JSON.stringify(obj.checkedRows);
console.log(newStr);
I have a string in JS in this format:
http\x3a\x2f\x2fwww.url.com
How can I get the decoded string out of this? I tried unescape(), string.decode but it doesn't decode this. If I display that encoded string in the browser it looks fine (http://www.url.com), but I want to manipulate this string before displaying it.
Thanks.
You could write your own replacement method:
String.prototype.decodeEscapeSequence = function() {
return this.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
return String.fromCharCode(parseInt(arguments[1], 16));
});
};
"http\\x3a\\x2f\\x2fwww.example.com".decodeEscapeSequence()
There is nothing to decode here. \xNN is an escape character in JavaScript that denotes the character with code NN. An escape character is simply a way of specifying a string - when it is parsed, it is already "decoded", which is why it displays fine in the browser.
When you do:
var str = 'http\x3a\x2f\x2fwww.url.com';
it is internally stored as http://www.url.com. You can manipulate this directly.
If you already have:
var encodedString = "http\x3a\x2f\x2fwww.url.com";
Then decoding the string manually is unnecessary. The JavaScript interpreter would already be decoding the escape sequences for you, and in fact double-unescaping can cause your script to not work properly with some strings. If, in contrast, you have:
var encodedString = "http\\x3a\\x2f\\x2fwww.url.com";
Those backslashes would be considered escaped (therefore the hex escape sequences remain unencoded), so keep reading.
Easiest way in that case is to use the eval function, which runs its argument as JavaScript code and returns the result:
var decodedString = eval('"' + encodedString + '"');
This works because \x3a is a valid JavaScript string escape code. However, don't do it this way if the string does not come from your server; if so, you would be creating a new security weakness because eval can be used to execute arbitrary JavaScript code.
A better (but less concise) approach would be to use JavaScript's string replace method to create valid JSON, then use the browser's JSON parser to decode the resulting string:
var decodedString = JSON.parse('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
// or using jQuery
var decodedString = $.parseJSON('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
You don't need to decode it. You can manipulate it safely as it is:
var str = "http\x3a\x2f\x2fwww.url.com";
alert(str.charAt(4)); // :
alert("\x3a" === ":"); // true
alert(str.slice(0,7)); // http://
maybe this helps: http://cass-hacks.com/articles/code/js_url_encode_decode/
function URLDecode (encodedString) {
var output = encodedString;
var binVal, thisString;
var myregexp = /(%[^%]{2})/;
while ((match = myregexp.exec(output)) != null
&& match.length > 1
&& match[1] != '') {
binVal = parseInt(match[1].substr(1),16);
thisString = String.fromCharCode(binVal);
output = output.replace(match[1], thisString);
}
return output;
}
2019
You can use decodeURI or decodeURIComponent and not unescape.
console.log(
decodeURI('http\x3a\x2f\x2fwww.url.com')
)