I want to ignore "\" in the dynamic value - javascript

When i am launching the web application it is generating a state token which is dynamic value looks like this"State_token_g0=stateToken = '00aF\x2D5HSbtfsCjJbYUAayevCC5uvH9Qg5aMGSUvKEM';" and it is getting failed and throwing an error as"{"errorCode":"E0000003","errorSummary":"The request body was not well-formed.","errorLink":"E0000003","errorId":"oaewNC2ocVjS6m_EpiszsjV7Q","errorCauses":[]}".
If the dynamic value generated without "" it is getting executed.
it is not possible to delete \ from the library as well.
Tried multiple regex ^[a-zA-Z0-9]+$, [^"]+?, \d+?,\w+?, {"stateToken":([^"]+?),^[A-Z0-9a-z\~!##$%^&()_+|,./<>?]+$,[A-Z0-9a-z\], ^[A-Z0-9a-z\]+$

replace(/\\/g, '');
will replace backslashes, could you add this to your regex?
let string = "00aF\x2D5HSbtfsCjJbYUAayevCC5uvH9Qg5aMGSUvKEM";
var minusbackslash = string.replace(/\\/g, '');
//show result in result div
document.getElementById("result").innerText = minusbackslash;
<div id="result"></div>

You can remove backslashes by adding a JSR223 PostProcessor after your Regular Expression Extractor and using the following code in the "Script" area:
vars.put('State_token_g0', vars.get('State_token_g0').replaceAll('\\\\',''))
The line will replace the original value of the State_token_g0 JMeter Variable with the removed slashes.
Demo:
In the above example vars stands for JMeterVariables class instance, see the JavaDoc for full description of all functions and fields and Top 8 JMeter Java Classes You Should Be Using with Groovy article for more details on this and other JMeter API shorthands available for the JSR223 Test Elements

Related

string.slice() not working on Server Side Javascript in ASPx

I am writing server side javascript code in aspx to pull out the 7 columns from CSV files which may or may not use quotes to enclose the data, depending on the file.
Currently, I am working on the code to remove the commas using javascript's string.sllice() for the first column, but is is returning an empty string.
Here is a sample line from the file. This is public info.
12/6/2017,8:30 AM,2013FA000060,In RE: the Support of: D.D.K. and A.P.C.,MH,Motion hearing,"Grill, Leo",State of Wisconsin,"Vesely, Tori A; Lawton, Mark David";
In working with my Regular expression based code for the first column, I have the correct expected string data for strTemp prior to the offending code:
12/6/2017,
Here is the code to remove the comma at the end:
cleanData = strTemp.slice(0, -1); // remove last 1 character
I have verified that strTemp is correct right before this statement is executed to make sure the string var assignments are not the problem (as seen above).
The expected result should be strTemp data without the comma at the end:
12/6/2017
I receive no errors. Just an empty string.
OK, so it looks like the data coming from the regular expression execute is not a string. Once I cast it to string it worked
cleanData = strTemp.toString().slice(0, -1);
I really do NOT like working with weakly typed languages!!

Javascript How to escape \u in string literal

Strange thing...
I have a string literal that is passed to my source code as a constant token (I cannot prehandle or escape it beforehand).
Example
var username = "MYDOMAIN\tom";
username = username.replace('MYDOMAIN','');
The string somewhere contains a backslash followed by a character.
It's too late to escape the backslash at this point, so I have to escape these special characters individually like
username = username.replace(/\t/ig, 't');
However, that does not work in the following scenario:
var username = "MYDOMAIN\ulrike";
\u seems to introduce a unicode character sequence. \uLRIK cannot be interpreted as a unicode sign so the Javascript engine stops interpreting at this point and my replace(/\u/ig,'u') comes too late.
Has anybody a suggestion or workaround on how to escape such a non-unicode character sequence contained in a given string literal? It seems a similar issue with \b like in "MYDOMAIN\bernd".
I have a string literal that is passed to my source code
Assuming you don't have any < or >, move this to inside an HTML control (instead of inside your script block) or element and use Javacript to read the value. Something like
<div id="myServerData">
MYDOMAIN\tom
</div>
and you retrieve it so
alert(document.getElementById("myServerData").innerText);
IMPORTANT : injecting unescaped content, where the user can control the content (say this is data entered in some other page) is a security risk. This goes for whether you are injecting it in script or HTML
Writing var username = "MYDOMAIN\ulrike"; will throw a syntax error. I think you have this string coming from somewhere.
I would suggest creating some html element and setting it's innerHTML to the received value, and then picking it up.
Have something like:
<div id="demo"></div>
Then do document.getElementById("demo").innerHTML = username;
Then read the value from there as document.getElementById("demo").innerHTML;
This should work I guess.
Important: Please make sure this does not expose the webpage to script injections. If it does, this method is bad, don't use it.

Javascript with Special Chartecter

I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with &apos;.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"

Store Html.Raw() in a string in Javascript, ASP.NET MVC 3

I'm using ASP.NET and I have a string of HTML in the database.
I want to get that html into a variable on the client.
If I do this:
var x = '#Html.Raw(myModel.FishValue)'
it works fine, because it's essentially doing
var x = '<p>hello!</p>';
however if there are quotes in the html it breaks the page.
My initial guess would be to .Replace the raw string to add escapes to the quotes, however both .ToString() and .ToHtmlString() (as Html.Raw returns an IHtmlString) do not produce the same markup as simple Html.Raw().
So I'm at a loss of what best to do.
What about replacing before calling the Html.Rawmethod?
var x = '#Html.Raw(myModel.FishValue.Replace("'","\\'"))'
UPDATE:
There might be other escape chars in the string coming from the model. For that reason I would recommend replacing the slashes first as well. Of course it all depends on what might come from the server in your model.
var x = '#Html.Raw(myModel.FishValue.Replace("\\","\\\\'").Replace("'","\\'"))'
A sample snippet representing the behavior in the javascript:
//Let's say my Model Content is > I'd Say \ is a escape character. You can't "Escape"
// YOu would have to replace ' --> \' and \ --> \\
var stringFromServer = 'I\'d Say \\ is a escape character. You can\'t "Escape"'
alert(stringFromServer)
Try this:
var x = '#(System.Web.HttpUtility.HtmlEncode(myModel.FishValue))';
If you need to decode the HTML on the client side use
unescape(x)
I think JQuery (not sure if you're using it or not) handles encoded HTML strings so you might not need unescape().
Try out the anti-xss library from Microsoft (which will be included I believe by default in asp.net 4.5):
AntiXss.JavascriptEncode(yourContent)
Anti-Xss is available 4.1 beta. If you want to use it in your application which I highly recommend, check out:
http://weblogs.asp.net/jgalloway/archive/2011/04/28/using-antixss-4-1-beta-as-the-default-encoder-in-asp-net.aspx

How do I extract the title value from a string using Javascript regexp?

I have a string variable which I would like to extract the title value in id="resultcount" element. The output should be 2.
var str = '<table cellpadding=0 cellspacing=0 width="99%" id="addrResults"><tr></tr></table><span id="resultcount" title="2" style="display:none;">2</span><span style="font-size: 10pt">2 matching results. Please select your address to proceed, or refine your search.</span>';
I tried the following regex but it is not working:
/id=\"resultcount\" title=['\"][^'\"](+['\"][^>]*)>/
Since var str = ... is Javascript syntax, I assume you need a Javascript solution. As Peter Corlett said, you can't parse HTML using regular expressions, but if you are using jQuery you can use it to take advantage of browser own parser without effort using this:
$('#resultcount', '<div>'+str+'</div>').attr('title')
It will return undefined if resultcount is not found or it has not a title attribute.
To make sure it doesn't matter which attribute (id or title) comes first in a string, take entire html element with required id:
var tag = str.replace(/^.*(<[^<]+?id=\"resultcount\".+?\/.+?>).*$/, "$1")
Then find title from previous string:
var res = tag.replace(/^.*title=\"(\d+)\".*$/, "$1");
// res is 2
But, as people have previously mentioned it is unreliable to use RegEx for parsing html, something as trivial as different quote (single instead of double quote) or space in "wrong" place will brake it.
Please see this earlier response, entitled "You can't parse [X]HTML with regex":
RegEx match open tags except XHTML self-contained tags
Well, since no one else is jumping in on this and I'm assuming you're just looking for a value and not trying to create a parser, I'll give you what works for me with PCRE. I'm not sure how to put it into the java format for you but I think you'll be able to do that.
span id="resultcount" title="(\d+)"
The part you're looking to get is the non-passive group $1 which is the '\d+' part. It will get one or more digits between the quote marks.

Categories

Resources