AngularJS format string inside double braces using replace() with regex - javascript

I am trying to format a MAC address in a table that is populated using AngularJS:
<tr ng-repeat="dev in devices">
<td>{{dev.mac.replace(/(.{2})/g,"$1:")}}</td>
</tr>
{{dev.mac}} works just fine (aside from being unformatted), but when I add the .replace() function it breaks. I tried escaping the forward slash based on the error I received, which didn't help. Is .replace() not available inside the browser or is there a different syntax for regex inside the double braces or what am I doing wrong?
The goal is to convert AABBCCDDEEFF into AA:BB:CC:DD:EE:FF as easily as possible within the double braces. As a bonus question, how do I prevent the trailing ':' in the regex (it currently prints AA:BB:CC:DD:EE:FF:)?
Edit: Adding the error message
Error: $parse:syntax
Syntax Error
Syntax Error: Token '/' not a primary expression at column 20 of the
expression [dev.mac.replace(/(.{2})/g,"$&:")] starting at
[/(.{2})/g,"$&:"].
That seems to indicate the forward slash is causing the problem, but like I said, escaping it doesn't help.

Rather than running your replace inline like that, it'd be better to abstract that out into a function, that should fix any issues you're having with it not getting interpreted correctly. This article shows the right syntax for declaring a function on the scope to call here: function call inside Angular double curly braces, it should be something like this
$scope.fixMacAddress = function(addr)
{
return addr.replace(/(.{2})/g,"$1:")
}
and
{{ fixMacAddress(dev.mac) }}

Related

Unterminated String error while iterating

This is my code :
<c:forEach items="${entry.value}" var="keyval">
var bdgroup= {
elem1: '${keyval.partno}',
elem2: '${keyval.location}',
elem3: '${keyval.village}',
elem4: '${keyval.id}'
};
exampleArray.push(bdgroup);
</c:forEach>
i am getting
'unterminated string literal error'`
sometimes it works fine but for other times this error happens..
When e.g. ${keyval.id} gets expanded, if it has a single quote in it, then the Javascript will look like
elem1: 'what's up?'
thus your unterminated string error.
Escape the quotes before you put them in JSON.
Escape the single quotes and any other special characters, so that the values are taken correctly.
I'm ==> I\'m
Looks like you're using a taglib, and the elements inside the single quotes are being generated by the page processor.
I'll bet that on the times that it fails, your values contain single quotes.
Escape the single quotes, and that should fix it.

Value unexpectedly changes while sending from jsp to javascript function

I have a piece of code in jsp:
String temp=new SimpleDateFormat("MMddyyyy").format((java.sql.Date)ppdates.get(authShown));
out.print(temp);
<select id="pcol<%=i%><%=weekNo%><%=au%>" onChange="pSelectedAuth(<%=i%>,<%=weekNo%>,<%=au%>,<%=currentEmployee%>,<%=temp%>)">
This prints 06042012 on the screen.
Now, my javascript functions are below:
function pSelectedAuth(formID,weekNo, index, currentEmployee,startDate){
alert(formID+":"+weekNo+":"+index+":"+currentEmployee+":"+startDate);
onchange, this alert shows 1623050
Does anyone has any idea how to get my 06042012 back?
You're not doing anything to quote your arguments (that is — you're not wrapping them in '...' or "..."), so they're being interpreted as JavaScript expressions. In JavaScript source-code, 06042012 is interpreted as a base-8 integer (because of the leading 0), so it denotes 1623050.
To fix this, be sure to wrap your JavaScript strings in '...' or "..." (as well as to properly escape any internal quotation-marks, backslashes, newlines, special characters, </, and so on). That way, you'll have '06042012' or "06042012", which JavaScript will interpret as a string, like you want.

jsonPath and unexpected illegal token

When passing the following string to jsonPath to filter a collection of objects:
$[?(en|**|(#.object.property.one=='other') && (#.object.property.two=='something(abc/def)'))]
I receive the following error:
jsonPath: Unexpected token ILLEGAL: (_v.object.property.one=='other') && (_v.object.property.two=='something(abc/def))
My initial guess is that the illegal character has something to do with round brackets or a forward slash present within a literal value. This might explain why a closing single quote around the last literal is missing. I have tried escaping both the round brackets and forward slash but to no avail. What would cause the filter method to throw the above exception?
Having a quick read over the jsonPath documentation it looks like brackets don't do the job you'd think.
In XPath, brackets are used to do groupings however in jsonPath they're used for script expressions (using whatever the underlying script engine is).
It could be that the value you're presenting as the script expression is invalid.

Too many quotes within quotes -- what to do?

Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";

Converting backslashes into forward slashes using javascript does not work properly?

I have a javascript variable comming from legacy system with backslashes into forward slashes:
'/46\465531_Thumbnail.jpg'
and I am trying to convert into this:
'/46/465531_Thumbnail.jpg'.
There is no way to fix the problem on the legacy system.
Here is the command I am running on IE8 browser:
javascript:alert("/46\465531_Thumbnail.jpg".replace(/\\/g,"/"));
as response I get:
---------------------------
Message from webpage
---------------------------
/46&5531_Thumbnail.jpg
---------------------------
OK
---------------------------
actually I just want to be translated as '/46/465531_Thumbnail.jpg'
What is wrong?
You need to double the backslash in your string constant:
alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));
If your legacy system is actually creating JavaScript string constants on your pages with embedded, un-quoted (that is, not doubled) backslashes like that, then it's broken and you'll have problems. However, if you're getting the strings via some sort of ajax call in XML or JSON or whatever, then your code looks OK.
It is actually interpreting \46 as an escape-code sequence for the character &. If you are going to hard-code the string, you need to escape the \:
alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));
^^ change \ to \\
Sample: http://jsfiddle.net/6QWE9/
The replacement part isn't the problem, it's the string itself. Your string:
"/46\465531_Thumbnail.jpg"
isn't /46\465531. Rather, the backslash is acting as an escape character. You need to change it to:
javascript:alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));
ie, escapeing the backslash with a backslash.
Nothing wrong with the replace. The input is wrong.
javascript:alert("/46\\465531_Thumbnail.jpg".replace(/\\/g,"/"));
^
\---------------- need to escape this!

Categories