javascript regex in chrome extension - javascript

Okay, a little context. I want to modify some crappy HTML on a page that I use a lot. I'm doing this via my content_script "js", as defined in the manifest.json file of the chrome extension. The primary method I've been using is this sort of ugly thing:
var str1 = 'something already on the page';
var str2 = 'something already on the page, plus some extra stuff';
document.body.innerHTML = document.body.innerHTML.replace(str,st2);
I'm mostly trying to re-order form objects, and expand them a little to show more information, and filter/condense them to be less superfluous. I'd appreciate any pointer as to a better way to do this.
Anyway... here's my specific problem.
I want to retrieve pistol (or any string) from the following:
<form action="map.cgi?use-o" method="post" class="a"><input type="submit" value="pistol" class="m"\></form>
I tried every variation of the following:
str.exec(/value="([^]+)" class/);
and I'm either getting null or junk strings that I don't want. Ideas?
Thanks!

If you insist on regex, then use below one:
(?:value=")([^"]+)
Here is DEMO
Using JavaScript it will look like:
var value = document.querySelectorAll("input[type=submit]")[0].value;

Related

How to find a dynamic node class by pattern in JavaScript

I'm working on this WP plugin and I've been trying to get the ID of a custom post kinda thing that is declared in the body class on each page. So it goes like this;
<body class="(Bunch of other classes) ld-courses-1731-parent">
I'm trying to get the number 1731 in my JS function but the number is dynamic so I need to some regex matching with the string pattern.
Pattern: ld-courses-*INT VALUE*-parent
how can I do this with JS? Any help is much appreciated thank you so much.
You can use match if thats the only class in your body:
var classList = document.getElementsByTagName("body")[0].classList;
[...classList].forEach(function(thisClass) {
if (/ld-courses-\b/.test(thisClass)) {
var id = thisClass.match(/\d/g);
console.log(id.join(""));
}
});
<body class="another-class-before another-class-12-hasnum ld-courses-1731-parent another-class-12-hasnumaswell another-class-after">
</body>
Hi Laclogan in regards to your question yes it's possible for sure.
Correct me if i'm wrong but the number comes probably if it's changing for each post directly from the url.
The following site explains if this is the case how to get that number from the url.
https://www.sitepoint.com/get-url-parameters-with-javascript/
In addition you can use the function concat to combine the strings see this site for an example hope it helps.
https://www.w3schools.com/jsref/jsref_concat_string.asp
Could you confirm for me that the number is always present in the url or if this is not the case?

Javascript regex to replace ampersand in all links href on a page

I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.

Extract data from url with JavaScript

EDIT_2: I forgot to specify its for Android app, so i dont think this is any use, i made a new post instead :( Added Android TAG..
EDIT: Im making an Android App
I need help to extract a number from an url, generated by JavaScript!
Site is:
http://www.oddsportal.com/sure-bets/
And the path looks like this:
<span class="logos l60"> </span>
<div class="odds-nowrp" xodd="xzoxfxzox">2.62</div> // <- 2.62 is the numer i need
For full path see this screenshot:
What library would do this best? (I know Jsoup cant do it) I have searched a few like:
HtmlUnit
Java Script Engine
Apache Commons BSF
Rhino
But i cant really make sense of it or find any examples for android which look like my problem
or find any examples for android which look like my problem
You need it for android?
Pretty much any library allowing DOM traversing will allow you to do this providing you know how to find your value.
is this value exactly at the same position in DOM every time?
is it wrapped by an easy to identify element? i.e. with a static ID
are there any other value that look alike in the DOM that you don't want?
Based on that, using JQuery for example, you could select it like this :
$('.table-main td.center > a[href^="/bookmaker"] + div[xodd]')
or this:
$('.table-main tr:nth-child(3) div.odds-nowrp[xodd]')
Use Jquery:
var number = $(".odds-nowrp").text();
you can just use regex if you have the url already in escaped string format
reg = /[A-z\"\>\<=?()0-9 \/]*(\d+.\d+)[A-z\"\>\<=?()0-9 \/]*/
reg.exec(url)[1] // this will return your number
if it's already rendered and the xodd value doesn't change, you could do something like this
document.querySelectorAll('.odds-nowrp[xodd=xzoxfxzox]')[0].innerText

Problem with regexp in userscript for chrome

This might be a noob question, but I have tried to find an answere here and on other sites and I have still not find the answere. At least not so that I understand enough to fix the problem.
This is used in a userscript for chrome.
I'm trying to select a date from a string. The string is the innerHTML from a tag that I have managed to select. The html structure, and also the string, is something like this: (the div is the selected tag so everything within is the content of the string)
<div id="the_selected_tag">
link
" 2011-02-18 23:02"
thing
</div>
If you have a solution that helps me select the date without this fuzz, it would also be great.
The javascript:
var pattern = /\"\s[\d\s:-]*\"/i;
var tag = document.querySelector('div.the_selected_tag');
var date_str = tag.innerHTML.match(pattern)[0]
When I use this script as ordinary javascript on a html document to test it, it works perfectly, but when I install it as a userscript in chrome, it doesn't find the pattern.
I can't figure out how to get around this problem.
Dump innerHTML into console. If it looks fine then start building regexp from more generic (/\d+/) to more specific ones and output everything into a console. There is a bunch of different quote characters in different encodings, many different types of dashes.
[\d\s:-]* is not a very good choice because it would match " 1", " ". I would rather write something as specific as possible:
/" \d{4}-\d{2}-\d{2} \d{2}:\d{2}"/
(Also document.querySelector('div.the_selected_tag') would return null on your sample but you probably wanted to write class instead of id)
It's much more likely that tag.innerHTML doesn't contain what you think it contains.

Escaping dilemma in Javascript

I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}

Categories