I am performing email address validation with javascript in a razor view page.
The regex I am going to use is similar to the one proposed at Validate email address in JavaScript?
However, because the regex contains an '#' character, I am getting parser error when try to run the web app.
my regex looks like
/^...otherpart #* ... other part$/
I tried to add an '#' character to make the in the origin regex ... ##* ..., this eliminated the compilation error but seems to make the regex stops working. (we have used it in another web app that does not use razor engine, so I know it works).
Is there any other way to escape the '#' character?
You can add another # in front of it to escape ##, try leaving out the quantifer *. If this doesn't seem to work then add <text></text> around the function, it tells Razor to not parse the contents. Alternatively you can put Javascript in a separate file to accomplish your needs.
If for some reason you have multiple ## in your string, place code blocks ahead #:##
Put the following inside the regEx instead of #:
#('#')
The above will be rendered to a single #.
Your example will become:
/^...otherpart #('#')* ... other part$/
Simply just use double ##.
It works for me and I think that is the only way.
It's better to use #('#') instead of ## (not working for me).
Example
<input class="form-control" pattern="^[a-zA-Z#('#')]{5,20}$"/>
Related
I have the following code which replaces the current URL using JavaScript:
window.location.replace(window.location.href.replace(/\/?$/, '#/view-0'));
However if I have a URL like:
domain.com/#/test or domain.com/#/
It will append the #/view-0 to the current hash. What I want to is replace EVERYTHING after the last part of the URL including any query strings or hashes.
So presume my regex doesn't handle that... How can I amend it, to be more aggressive?
The following syntax may help:
location.href.replace(/[?#].*$/, '#/view')
It will replace everything after (and together with) ? or # in the string with #/view.
(^[^\/]*?\/)(?:.*)
Use this.Replace by \1 then your string
See demo.
http://regex101.com/r/sA7pZ0/28
I'm trying to dynamically add contents of a div using JS. Back end is Ruby on Rails. I am having a problem. Here's what is included in the view file:
var product_sidebar_inner = "<%= CGI.escapeHTML(render(...some partial...)).gsub(/\r/," ").gsub(/\n/," ") %>";
document.getElementById("left_sidebar_wrapper").innerHTML = unescape(product_sidebar_inner);
The above inserts html as text to div#left_sidebar_wrapper. Spent some time on this but still can't make this work. Any idea what am I am doing wrong?
Based on your comment to macarthy, I think you want CGI.escape (or CGI.unescape), that's what you use for URL encoding. You can also use URI.escape (or URI.unescape) but you'll get tired of having to pass the unsafe regex all the time to get it to do what you want.
Also, on the JavaScript side, you should be using encodeURI or encodeURIComponent as escape is deprecated because it has problems with non-ASCII characters.
THink you need to use raw
unescape(raw(product_sidebar_inner));
Does javascript regular expressions support backreferences inside character class?
I want to do something like this:
htmlString.replace(/attribute_name=(['"])[^\1]*\1/,'')
But that does not work. This does:
htmlString.replace(/attribute_name=(['"])[^'"]*\1/,'')
Unfortunatelly my attribute_name can contain apostrophes or quotes, so I need to exlude the actual quoting character from the inside of the attribute, but leave the other one.
I can't be sure which one is used. I can safely assume that quotes are in form of entity, but still there can be apostrophes inside:
<div attribute_name="John's car" class="someClass"></div>
<div attribute_name='some "quoted text"' class="someClass"></div>
I am not able to predict which of " or ' will be used around the attribute.
How to get rid of the attribute and leave the class attribute alone (not cut too much)?
context:
I am getting the html by $('templateContainer').innerHTML . I have to modify that html before inserting it into the page again. I have to cut some non-standard attibutes and all the ID attributes.
I agree with the other answers in that I don't think that the attributes are the place to do this type of thing, but I'm also wary of recommending the DOM either. I just feel dirty when I do that, I don't know why.
I usually will try to use a javascript object to store my data in and then reference it using well-formed keys, etc. shrug It's more work, but it's cleaner IMHO. But, it definitely isn't the only way to accomplish the task.
As to your question, you could also use the non-greedy matching in JavaScript and it would look like this:
htmlString.replace(/ ?attribute_name=(['"]).*?\1/, '')
Regular Expressions in JavaScript | evolt.org
You'd be a LOT better off using DOM or some other actual model designed for hierarchical content. That said, if you must use regex, the simplest way would probably be to just use a | (OR) instead.
htmlString.replace(/attribute_name=('[^']*'|"[^"]*")/,'')
The reason for this "escapes" me.
JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"}.
Why?
JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required, like Harold L points out:
The JSON spec says you CAN escape forward slash, but you don't have to.
Harold L answered Oct 16 '09 at 21:59
Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out:
This is because HTML does not allow a string inside a <script> tag to contain </, so in case that substring's there, you should escape every forward slash.
Seb answered Oct 16 '09 at 22:00 (#1580667)
Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)
The JSON spec says you CAN escape forward slash, but you don't have to.
I asked the same question some time ago and had to answer it myself. Here's what I came up with:
It seems, my first thought [that it comes from its JavaScript
roots] was correct.
'\/' === '/' in JavaScript, and JSON is valid JavaScript. However,
why are the other ignored escapes (like \z) not allowed in JSON?
The key for this was reading
http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by
http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of
the slash escape allows JSON to be embedded in HTML (as SGML) and XML.
PHP escapes forward slashes by default which is probably why this appears so commonly. I suspect it's because embedding the string "</script>" inside a <script> tag is considered unsafe.
Example:
<script>
var searchData = <?= json_encode(['searchTerm' => $_GET['search'], ...]) ?>;
// Do something else with the data...
</script>
Based on this code, an attacker could append this to the page's URL:
?search=</script> <some attack code here>
Which, if PHP's protection was not in place, would produce the following HTML:
<script>
var searchData = {"searchTerm":"</script> <some attack code here>"};
...
</script>
Even though the closing script tag is inside a string, it will cause many (most?) browsers to exit the script tag and interpret the items following as valid HTML.
With PHP's protection in place, it will appear instead like this, which will NOT break out of the script tag:
<script>
var searchData = {"searchTerm":"<\/script> <some attack code here>"};
...
</script>
This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.
Yes, some JSON utiltiy libraries do it for various good but mostly legacy reasons. But then they should also offer something like setEscapeForwardSlashAlways method to set this behaviour OFF.
In Java, org.codehaus.jettison.json.JSONObject does offer a method called
setEscapeForwardSlashAlways(boolean escapeForwardSlashAlways)
to switch this default behaviour off.
I wonder if there is a way to use ungreedy matching in JavaScript? I tried the U modifer, but it doesn't seem to work.
I want to write a small BBCode parser in JavaScript, but without ungreedy matching it isn't possible (at least as far as I see it) to do something like this:
'[b]one[/b] two [b]three[/b]'.replace( /\[b\](.*)\[\/b\]/, '<b>$1</b>' );
But such a replacement would be nice since there is no need to check for HTML validity then. Unclosed markups will stay simple text.
You can use ? after * or + to make it ungreedy, e.g. (.*?)
I'm late, but I'll post the regex anyway.
'[b]one[/b] two [b]three[/b]'.replace( /\[b\](.+?)\[\/b\]/g, '<b>$1</b>' );