Javascript replace query string + with a space - javascript

I'm grabbing the query string parameters and trying to do this:
var hello = unescape(helloQueryString);
and it returns:
this+is+the+string
instead of:
this is the string
Works great if %20's were in there, but it's +'s. Any way to decode these properly so they + signs move to be spaces?
Thanks.

The decodeURIComponent function will handle correctly the decoding:
decodeURIComponent("this%20is%20the%20string"); // "this is the string"
Give a look to the following article:
Comparing escape(), encodeURI(), and encodeURIComponent()

Adding this line after would work:
hello = hello.replace( '+', ' ' );

Related

Escaping apostrophe (single quote) character in javascript and html

I have a following situation:
I compose a string in javascript that include apostrophe character. That string is actually html code that is later attached to html using innerHTML method. So the code looks something like this:
var str = 'link'; (argument of the foo function is string)
And after that, this string is inserted into some html element like this:
dataHolder.innerHTML = str;
I've tried to escape ' character with ', ' and \u0027 but all of that is rendered as ' after innerHTML method is called, so when the method foo from the example above is called by clicking on link I always get javascript error saying: Uncaught SyntaxError: missing ) after argument list
You need to have both ' and " in your string, so you will need a third way to delcare a string, you can use template strings for that. Declare your ba'r string as a template string and escape its apostrophe using a backslash \:
document.querySelector('#myDiv').innerHTML =
'link';
function foo(data) {
console.log(data);
}
<div id="myDiv"></div>
use \' instead of ' inside the string, so it should be
var str = 'link';
However, this code is just correct in string format aspect. I think what you want could be
var str = 'link';
You can also use the backtick ` to avoid this problem:
var str = `link`;

Parsing string as JSON with single quotes?

I have a string
str = "{'a':1}";
JSON.parse(str);
VM514:1 Uncaught SyntaxError: Unexpected token '(…)
How can I parse the above string (str) into a JSON object ?
This seems like a simple parsing. It's not working though.
The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.
I know it's an old post, but you can use JSON5 for this purpose.
<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works.
Eval is not evil when it is used on data you have control over.
For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
Using single quotes for keys are not allowed in JSON. You need to use double quotes.
For your use-case perhaps this would be the easiest solution:
str = '{"a":1}';
Source:
If a property requires quotes, double quotes must be used. All
property names must be surrounded by double quotes.
var str = "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);
This solved the problem for me.
Something like this:
var div = document.getElementById("result");
var str = "{'a':1}";
str = str.replace(/\'/g, '"');
var parsed = JSON.parse(str);
console.log(parsed);
div.innerText = parsed.a;
<div id="result"></div>
// regex uses look-forwards and look-behinds to select only single-quotes that should be selected
const regex = /('(?=(,\s*')))|('(?=:))|((?<=([:,]\s*))')|((?<={)')|('(?=}))/g;
str = str.replace(regex, '"');
str = JSON.parse(str);
The other answers simply do not work in enough cases. Such as the above cited case: "title": "Mama's Friend", it naively will convert the apostrophe unless you use regex. JSON5 will want the removal of single quotes, introducing a similar problem.
Warning: although I believe this is compatible with all situations that will reasonably come up, and works much more often than other answers, it can still break in theory.
sometimes you just get python data, it looks a little bit like json but it is not. If you know that it is pure python data, then you can eval these data with python and convert it to json like this:
echo "{'a':1}" | /usr/bin/python3 -c "import json;print(json.dumps(eval(input())))"
Output:
{"a": 1}
this is good json.
if you are in javascript, then you could use JSON.stringify like this:
data = {'id': 74,'parentId': null};
console.log(JSON.stringify(data));
Output:
> '{"id":74,"parentId":null}'
If you assume that the single-quoted values are going to be displayed, then instead of this:
str = str.replace(/\'/g, '"');
you can keep your display of the single-quote by using this:
str = str.replace(/\'/g, '\&apos;\');
which is the HTML equivalent of the single quote.
json = ( new Function("return " + jsonString) )();

Get a substring from a string for a regular expression in JavaScript

I have a string of the following form:
data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data
It can be in different languages, but in any case I need to get a string which is between the characters ' '
That is, in the example above, I need to get the following string:
view-7631b26ea80b1b601c313b15cc4e2ab03faedf30
Can I do this using the method string.replace(regexp, str) ?
I've highlighted the desired line using the following regular expression:
/'\b(.*)\b'/gm
Now, using the method string.replace I need to delete everything except that...
Got any suggestions?
Use match method.
var data = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
data = data.match(/'\b(.*)\b'/gm)
You have good solid anchor text in either side, so:
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
Live Example:
var str = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
document.body.innerHTML =
"<pre>Got: [" + substr + "]</pre>";
But again, as I said in a comment, using a simple regular expression to extract information from HTML is usually doomed to fail. For instance, you probably don't want to match this:
<p>The string is data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'</p>
...and yet, a simple regex solution will do exactly that. To properly handle HTML, you must use a proper HTML parser.
You can also try this one:
/\'([^\']+)\'/gm

Remove new line characters from data recieved from node event process.stdin.on("data")

I've been looking for an answer to this, but whatever method I use it just doesn't seem to cut off the new line character at the end of my string.
Here is my code, I've attempted to use str.replace() to get rid of the new line characters as it seems to be the standard answer for this problem:
process.stdin.on("data", function(data) {
var str;
str = data.toString();
str.replace(/\r?\n|\r/g, " ");
return console.log("user typed: " + str + str + str);
});
I've repeated the str object three times in console output to test it. Here is my result:
hi
user typed: hi
hi
hi
As you can see, there are still new line characters being read between each str. I've tried a few other parameters in str.replace() but nothing seems to work in getting rid of the new line characters.
You are calling string.replace without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value.
Try this:
...
str = str.replace(/\r?\n|\r/g, " ");
...
However, if you actually want to remove all whitespace from around the input (not just newline characters at the end), you should use trim:
...
str = str.trim();
...
It will likely be more efficient since it is already implemented in the Node.js binary.
You were trying to console output the value of str without updating it.
You should have done this
str = str.replace(/\r?\n|\r/g, " ");
before console output.
you need to convert the data into JSON format.
JSON.parse(data) you will remove all new line character and leave the data in JSON format.

Use Greasemonkey to add bold tags to dates on a page?

I have a Greasemonkey script that prints a div -- works! However, I'd like to be able to add bold tags to all dates in this div.
Dates are formatted MM/DD/YYYY
So something like:
var regex = '\d{2}\/\d{2}\/\d{4}';
Then how would I perform the search replace? If the div was called loanTable:
Non-working concept:
$("#loanTable").html().replace( regex, "<b>" regex "</b>" )
Something like the above should work but I'm not sure of the exact syntax for this.
Use a regex capture group:
var loanTable = $("#loanTable")
var loanHTML = loanTable.html ().replace (/(\d{2}\/\d{2}\/\d{4})/g, "<b>$1</b>");
loanTable.html (loanHTML);
This piece of code is not valid JS:
var regex = '\d{2}\/\d{2}\/\d{4}';
$("#loanTable").html().replace( regex, "<b>" regex "</b>" )
The syntax for regex is /regex/, non quoted, or new Regex('regex') with quotes.
Start by assigning the html to a variable. Also <b> is barely used anymore, <strong> is the new standard. Then, replace() takes a regex and a string or function as parameters. To replace multiple times you have to use the g flag. Finally, to do what you want to accomplish you can use replacement tokens, like $1 etc...
var re = /\d{2}\/\d{2}\/\d{4}/g; // 'g' flag for 'global';
var html = $("#loanTable").html();
$("#loanTable").html(html.replace(re, '<strong>$&</strong>')); // The `$&` token returns the whole match
Last time I used GreaseMonkey, it wasn't easy to get jQuery to run in your user scripts.
Use the following code to do it without jQuery:
var loanTable = document.getElementById('loanTable');
loanTable.innerHTML = loanTable.innerHTML.replace(/(\d{1,2}\/\d{1,2}\/\d{4})/g, "<b>$1</b>");
One small aspect of this: you need to concatenate strings with a + operator:
$("#loanTable").html().replace( regex, "<b>" + regex + "</b>" )

Categories