Swift evaluate JavaScript in webview - javascript

Why, when I change this function variable "endc" to normal text example
let endc = "here is path as string"
then is working - when I want to get "path" from function then my code is broken
there is my problem - why?

The + operator is overloaded for String class, so both the operand must be String for it to work.
Here your variable endc is type of URL. So the + doesn't work for String and URL.
Better to convert your URL into string and then use +, like this:
var welcome = js + endc.absoluteString + typer
Now, it should work.
Also, I think you should add your semicolon in the typer string itself.

Related

Break out from JavaScript variable

So, I have the following code:
<script type="text/javascript">
var name = prompt("What's your name?");
var greeting = "Hello " + name + " :D";
console.log(greeting);
</script>
I am trying to break out from name variable. For example: answering the question by
"alert(1);\\
In browser console, printing name variable shows the following:
Now, when trying to create a second variable with the same content it produces an error.
Why does "name" contain invalid syntax content? and is there any way to break out from the variable in this scenario?
When you input "alert(1);\\ in the prompt, the special characters are automatically escaped and the input is assigned to name, but when you are doing that via the console or a script, you have to escape the characters manually. Since you wrote the string using double-quotes, the correct way to do the assignment would be:
var test = "\"alert(1);\\\\";
When uing single-quotes, you wouldn't have to escape the double-quotes:
var test = '"alert(1);\\\\';
What I did here is escape the required characters by putting a \ before them. What you see when you try to view the value of name is the actual content without the escaping.
JavaScript believes that you are ending the string literal at the second quotation mark.
Two possible solutions:
Wrap with single quotes: test = '"alert(1)\\'
Escape the second quote: test = "\"alert//"

How do I replace the html objects with it's text content?

I'm trying to replace link parameters with the query strings and I'm a noob when it comes to web dev
I've tried String(), object.textContent() and some more things but can't seem to get what I want
here's my code:
link="https://someWebsite?phone=replace1&message=replace2"
link = link.replace("replace1",phone); //phone is an input box returned by document.getElementByID() method
link = link.replace("replace2",message); //message is a text area returned by document.getElementByID() method
expected link: https://someWebsite?phone=123456&mesaage=somemessage
actual link: https://someWebsite?phone= [object HTMLInputElement]&message=[object HTMLTextAreaElement]
To get the value of an input, you use its value. Also, in query strings, you must encode query parameters with encodeURIComponent¹. So:
link="https://someWebsite?phone=replace1&message=replace2"
link = link.replace("replace1",encodeURIComponent(phone.value));
link = link.replace("replace2",encodeURIComponent(message.value));
Also note that each of those will replace the first occurrence, not all occurrences. See this question's answers if you need to replace each of those (replace1, replace2) in more than just the first place it appears.
Of course, with the code you've shown, it would make more sense not to use replace at all:
link = "https://someWebsite?phone=" + encodeURIComponent(phone.value) +
"&message=" + encodeURIComponent(message.value);
Or with ES2015+:
link = `https://someWebsite?phone=${encodeURIComponent(phone.value)}&message=${encodeURIComponent(message.value)}`;
¹ You have to encode the names, too, but encodeURIComponent("phone") is "phone" and encodeURIComponent("message") is "message", so... But if you had other characters in there, such as [], you'd need to encode them.
In jQuery we use backticks and ${} for string interpolation:
`some text ${replacedtext} some other text`
If you're using vanilla javascript use + signs for string interpolation:
"some text" + replacedtext + "some other text"
Hope this helps

Regex to find urls with hashes and exclamation marks #! [duplicate]

I know this has been asked a thousand times before (apologies), but searching SO/Google etc I am yet to get a conclusive answer.
Basically, I need a JS function which when passed a string, identifies & extracts all URLs based on a regex, returning an array of all found. e.g:
function findUrls(searchText){
var regex=???
result= searchText.match(regex);
if(result){return result;}else{return false;}
}
The function should be able to detect and return any potential urls. I am aware of the inherant difficulties/isses with this (closing parentheses etc), so I have a feeling the process needs to be:
Split the string (searchText) into distinct sections starting/ending) with either nothing, a space or carriage return either side of it, resulting in distinct content chunks, e.g. do a split.
For each content chunk that results from the split, see whether it fits the logic for a URL of any construction, namely, does it contain a period immediately followed the text (the one constant rule for qualifying a potential URL).
The regex should see whether the period is immediately followed by other text, of the type allowable for a tld, directory structure & query string, and preceded by text of the allowable type for a URL.
I am aware false positives may result, however any returned values will then be checked with a call to the URL itself, so this can be ignored. The other functions I have found often dont return the URLs query string too, if present.
From a block of text, the function should thus be able to return any type of URL, even if it means identifying will.i.am as a valid one!
eg. http://www.google.com, google.com, www.google.com, http://google.com,
ftp.google.com, https:// etc...and any derivation thereof with a query string
should be returned...
Many thanks, apologies again if this exists elsewhere on SO but my searches havent returned it..
I just use URI.js -- makes it easy.
var source = "Hello www.example.com,\n"
+ "http://google.com is a search engine, like http://www.bing.com\n"
+ "http://exämple.org/foo.html?baz=la#bumm is an IDN URL,\n"
+ "http://123.123.123.123/foo.html is IPv4 and "
+ "http://fe80:0000:0000:0000:0204:61ff:fe9d:f156/foobar.html is IPv6.\n"
+ "links can also be in parens (http://example.org) "
+ "or quotes »http://example.org«.";
var result = URI.withinString(source, function(url) {
return "<a>" + url + "</a>";
});
/* result is:
Hello <a>www.example.com</a>,
<a>http://google.com</a> is a search engine, like <a>http://www.bing.com</a>
<a>http://exämple.org/foo.html?baz=la#bumm</a> is an IDN URL,
<a>http://123.123.123.123/foo.html</a> is IPv4 and <a>http://fe80:0000:0000:0000:0204:61ff:fe9d:f156/foobar.html</a> is IPv6.
links can also be in parens (<a>http://example.org</a>) or quotes »<a>http://example.org</a>«.
*/
https://github.com/medialize/URI.js
http://medialize.github.io/URI.js/
You could use the regex from URI.js:
// gruber revised expression - http://rodneyrehm.de/t/url-regex.html
var uri_pattern = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
String#match and or String#replace may help…
Following regular expression extract URLs from string (inc. query string) and returns array
var url = "asdasdla hakjsdh aaskjdh https://www.google.com/search?q=add+a+element+to+dom+tree&oq=add+a+element+to+dom+tree&aqs=chrome..69i57.7462j1j1&sourceid=chrome&ie=UTF-8 askndajk nakjsdn aksjdnakjsdnkjsn";
var matches = strings.match(/\bhttps?::\/\/\S+/gi) || strings.match(/\bhttps?:\/\/\S+/gi);
Output:
["https://www.google.com/search?q=format+to+6+digir&…s=chrome..69i57.5983j1j1&sourceid=chrome&ie=UTF-8"]
Note:
This handles both http:// with single colon and http::// with double colon in string, vice versa for https, So it's safe for you to use. :)
try this
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
you could use this website to test regexp http://gskinner.com/RegExr/
In UIPath Studio the following built-in regex rule has been defined:
/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-a-zA-Z0-9+&##\/%=~_|$?!:,.]*\)|[-a-zA-Z0-9+&##\/%=~_|$?!:,.])*(?:\([-a-zA-Z0-9+&##\/%=~_|$?!:,.]*\)|[a-zA-Z0-9+&##\/%=~_|$])/

jquery .replace(/./g, "") do not work for me but others

I found this snippet somewhere and it works like a charm:
var n = parseInt(e.find("span.favNum").text().replace(/./g, "")) + 1;
If I do it in a similar way it doesn't work anymore.
I do the following:
<div id ="test">6.987</div>
var test = $("#test");
var r = test.text().replace(/./g, "");
console.log("wrong ", r);
I know that I can replace it also like this:
var r = test.text().replace(".", "");
This works.
I would like to understand why the "stolen" snippet is working.
Any idea?
http://jsfiddle.net/nJZMf/3/
The original script is found here: http://wp-svbtle.themeskult.com/
You will find the snippet by viewing the source of index.html and searching for .replace.
You need to escape the "."
test.text().replace(/\./g, "");
The reason that the code in the page you linked to works, where yours doesn't, is that it's not the same regular expression. Here's what I found in that page (and similar code in several places)
r = n.text().replace( /,/g, "" )
where r is a jQuery object.
Note that the regular expression has a , inside the //, not a . like the code you had trouble with.
Comma is not a special character in regular expressions, so it needs no special treatment. Period has a special meaning. As the other answers pointed out, it matches all characters, and you need to prefix it with \ if you want to match . only.
Also note that .replace() is not jQuery code, it's JavaScript.
jQuery's .text() method returns a JavaScript String value. So anything you do with that string - such as the .replace() call - is actually a JavaScript String method.
The distinction is important when you want to research a problem: a search for "javascript string replace" will get you better information than "jquery replace".
It has to be var r = test.text().replace(/\./g, ""); instead of var r = test.text().replace(/./g, ""); because you need to escape the . in order for it to be replaced.
http://jsfiddle.net/mrk1989/nJZMf/4/
Solution because I add \ in var r = test.text().replace(/\./g, "");
The problem was that you did not escape dot.
But keep in mind that:
.replace(".", "");
.replace(/\./g, "");
are two different things.
For example: https://jsfiddle.net/rmhpkz9n/1/

Why do you need the + between variables in javascript?

Why does this line work
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
but not this one
$('#body-image').css("background-image", 'url('backgroundimage')');
or this one
$('#body-image').css("background-image", 'url(backgroundimage)');
backgroundimage is a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string together with a variable, you do 'some string ' + someVariable. Without the +'s, JavaScript wouldn't know what to do with your variable (and in your third example, wouldn't even know that it was a variable).
You need to concat the string with the variable backgroundimage. So you use "+" for this.
That's why this doesn't work.
$('#body-image').css("background-image", 'url('backgroundimage')');
And the secont doesn't work because there is no image called 'backgroundimage'.
$('#body-image').css("background-image", 'url(backgroundimage)');
Because you are building a string. You are missing the line where backgroundimage gets a value:
var backgroundimage = "someimage.gif";
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
becomes:
$('#body-image').css("background-image", 'url(someimage.gif)');
it's concatenating the string.
let's say backgroundimage is 'foo.jpg, then
'url('+backgroundimage+')' = 'url(foo.jpg)'
In JavaScript, a string literal (i.e., "I am a string") is actually treated like a String object (though, strictly speaking, it isn't - see the MDC documentation - but we can ignore the difference at this level). The following two lines are equivalent:
var letters = "ABC", numbers = "123";
var letters = new String("ABC"), numbers = new String("123");
Strings are concatenated using either the + operator or the String.concat method, either of which join 2 or more strings in a left-to-right order and return the result. So in order to get "ABC123", we can do any of the following:
"ABC" + "123"
"ABC" + numbers
letters + "123"
letters + numbers
"ABC".concat("123")
"ABC".concat(numbers)
letters.concat("123")
letters.concat(numbers)
but not:
letters"123"
"ABC"numbers
lettersnumbers
"lettersnumbers"
which are all, effectively, the same thing that you were trying to do in your examples.

Categories

Resources