how convert uppercase node into lowercase in ckeditor? - javascript

when i use user defined tags with uppercase node like "<ABC> test </ABC>" in ckeditor .On clicking source, it gets displayed as "<abc> test </abc>".please help me to get the expected output , which should be <ABC> test </ABC> and please guide me where the code should be modified.Thanking you

(Continued from comments) I propose post-processing the content and not trying to bend CKEditor to produce Case Sensitive output.
I don't know your languages or your architecture, but if you get the data from CKEditor with getData(), you can do something like this if you want to do the conversion in the client side:
// Javascript
var i = CKEDITOR.instances.editor1;
var d = i.getData();
var correctData = d.replace(/<abc/ig, '<ABC');
In the backend you can do something similar
// C# (untested)
string result = Regex.Replace(
htmlStringFromAJAX,
RegEx.Escape("<abc"),
RegEx.Escape("<ABC"),
RegexOptions.IgnoreCase
);
// PHP (untested)
$result = str_ireplace("<abc", "<ABC", $htmlStringFromAJAX);
(I hope you either have just this one abc tag or a small static amount of tags - if not, this will be a very annoying solution to maintain.)

Related

AEM <a href> not working when using JavaScript to concatenate string with currentPage.path

I'm creating a project in Adobe Experience Manager and have run into problems in the implementation of my language switching component. The component is supposed allow the user to click on a link and have the language of the page change. For example, if they are on the English page /content/myproject/en/home.html and they click it, they are supposed to end up on /content/myproject/fr_ca/home.html.
As part of getting it up and running, I was trying to concatenate currentPage.path and "/profile.html" so that I could at least get the component to register some change to the string in the tag.
From the English home.html page, currentPage.path produces the string "/content/myproject/en/home". Concatenating it with /profile.html should produce the string "/content/myproject/en/home/profile.html" which it does if I use Sightly to do something like <p>${langinfo.goToPage}</p>.
However, if I try this: the component will show a blank anchor tag. It will also blank anything I've written in between the two anchor tags.
So far I've tried returning a string I've written out by hand "/content/myproject/en/home/profile.html" as the goToPage value and it works in the anchor tag. Also, if I only return currentPage.path it works. It refuses to work like this if I try to concatenate but it will work like this: <a>It works here!.
The best I can figure at this point is that currentPage.path is a Java String object that is being accessed by JavaScript and there are problems when JS tries to type it to a JavaScript string with +. It also doesn't work if I try to cast the statement as a string with either String(goToPage) or goToPage.toString(). It doesn't seem to matter when I cast it as a string. One blog I looked at seemed to hint that this was a problem with Rhino and that I should do a .toString() after the initial concatenation. That didn't work. Another post on stackOverflow seemed to point out that it could be a problem trying to concatenate a Java String object in JavaScript and pointed out that this should be taken into account but didn't go into how to deal with the issue.
I appending to a string isn't the intended end functionality of my component, but if I can't modify the string by concatenating, seems like I can hardly do a search and replace to change /en/ to /fr-ca/. If anyone has a more elegant solution to my problem than what I'm attempting, that would be appreciated as much as a fix for what I'm working on.
I've pasted my code here (as suggested) and posted screenshots of my code to help.
Javascript:
use(function() {
var pageLang = currentPage.properties.get("jcr:language", "en");
var otherLangText;
var currPage = currentPage.name;
var currPagePath = currentPage.path;
var goPage;
if (pageLang == "fr_ca") {
otherLangText = "English";
goPage = "/content/myproject/en/index/home.html";
} else {
otherLangText = "Français";
goPage = "/content/myproject/fr-ca/home/home.html";
};
return {
otherLanguage: otherLangText,
goToPage: goPage
}
})
HTML:
<nav data-sly-use.langinfo="langcontact.js">
<ul class="lang-list-container">
<li class="lang-list-item">${langinfo.otherLanguage}</li>
<li class="lang-list-item">Contact</li>
</ul>
</nav>
I'm pretty stumped here. What am I doing wrong?
The line <li class="lang-list-item">${langinfo.otherLanguage}</li>
should actually be -
<li class="lang-list-item">${langinfo.otherLanguage}</li>
What you are trying to do is pass an object to object which will not work, in case you want to pass the extension to be used in JS you need to do that in the USE call. Refer to the samples in this blog.
Update -
You code works fine for me as long as the link is valid.
use(function() {
var pageLang = currentPage.properties.get("jcr:language", "en");
var otherLangText;
var currPage = currentPage.name;
var currPagePath = currentPage.path;
var goPage;
if (pageLang == "fr_ca") {
otherLangText = "English";
goPage = currPagePath+"/profile.html";
} else {
otherLangText = "Français";
goPage = currPagePath+"/profile.html";
};
return {
otherLanguage: otherLangText,
goToPage: goPage
}
})
The only possible reason you are getting empty href is because your link is not valid and thus linkchecker is removing it. If you check on author instance you will see broken link symbol along with your link text.
Ideally you should fix the logic so that proper valid link is generated. On development you could disable the linkchecker and/orlink transformer to let all links work (even invalid ones | not recommended). The two services can be checked in http://localhost:4502/system/console/configMgr by searching for - Day CQ Link Checker Service and Day CQ Link Checker Transformer

replacing specific characters in strings

pretty simple:
i have mathematical problems stored in a DB, like 3+6, 5*3, 4-2 etc.
i want the output to show proper mathematical ×s instead of * (and ÷ instead of /).
but they have to be stored in the DB with * and / for obvious reasons (being "normal" characters vs. html entities in DB and especially for mathjs to be able to solve them from string)
so i am looking for a way to change them in the html output.
first i thought about something with css, but that would probably mean i'd have to have a class for them (or is it possible?).
then i thought i could do it with jS/jQuery. but it feels overly complicated at first.
how would you do this?
(server is running node.js + jade. the strings come from the db and are rendered directly on the page, so i need a way to change the symbols "afterwards")
You don't necessarily have to store the characters as HTML entities. So long as you include the appropriate charset meta tag, then you'll be able to use unicode symbols in your page.
<meta charset='utf-8'>
If you can't store them in the database as unicode, then you'll have to programatically fix the strings afterwards.
var replacementSymbols: {
'*': '×',
'/': '÷'
};
function replaceInString(equation) {
var targetSymbols = Object.keys(replacementSymbols);
return targetSymbols.reduce(function(string, symbol) {
var replacement = replacementSymbols[symbol];
return string.replace(symbol, replacement);
}, equation);
}
What you're attempting to do is not really possible with CSS.
You could use JavaScript's string replace method to achieve this instead.
for instance:
var str = "5*6"
var res = str.replace("*", "×");
http://www.w3schools.com/jsref/jsref_replace.asp
When you're writing your html, you can insert a <span class='multiply'></span> for each *
Then you can do:
$("span.multiply").html("×");
And then you you would do the same with division, and so on.
EDIT
You could also try something like this:
var newHtml = $('body').html().replace(/\*/g, "×");
$('body').html(newHtml);
Unless you're using something like Angular and a filter to parse the string, something like this might be the best option. If you're not able to insert classes before the page is rendered, you may need to see if the rendered data is wrapped in something like <pre/> tag so that you can use the appropriate selector:
template
<div class="math-expression">
3 * 4 = 12
</div>
logic
document.querySelectorAll('.math-expression').forEach(
function( elem, i, arr){
s = elem.textContent
elem.textContent = s.replace( /\*/g, 'x' )
}
)
note
I didn't test this as I normally just use Angular filters for these types of text renderings.

Passing Applescript list to javascript ExtendScript as array for Indesign

Background
I have a load of Applescripts(AS) which designers use with InDesign that help process the workflow for production. There is a great deal of OS interaction that the AS does that the JavaScript can not, so moving away from AS is not possible.
Due restrictions I am unable to install pretty much anything.
I am unable to update anything. Script Editor and ExtendScript Tool Kit are what I have to work with.
Operating Environment:
OS X 10.8.5 &
Adobe CS6
How it works
User preferences are saved as Properties in local Applescripts saved in the user's documents folder.
###property grabber.scpt
set mypath to path to documents folder
set mypropertiesfile to ((mypath & "myproperties.scpt") as string)
set thePropertyScript to load script file mypropertiesfile
set designerinitials to (designerinitials of thePropertyScript) ETC...
Some of the properties are AS lists.
Why I need JS?
I'm making palettes and would prefer to use the ScriptUI rather than do it all in AS like this:
set dlgRef to make dialog with properties {name:"User Settings", can cancel:true, label:"Dialog Label"}
The string the AS hands off to the JS is this:
{"myname",{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"},{firstvalue:"test2", secondvalue:"val2", thirdvalue: "val3"}}
These are not lists, but text...
The JS
myAppleScript = new File("valid_path_to/property grabber.scpt");
var myreturn = app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage);
var myname = myreturn[0];
var firstlist = myreturn[1];
var secondlist = myreturn[2];
ExtendScript data browser shows:
firstlist = {firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}
It is not an array...
I have tried using https://github.com/KAYLukas/applescript-json
to json encode the lists, but the same result.
firstlist = [{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}]
I have also made it much simpler with just
firstlist = {"test","val2","val3"}
Still the JS treats it as a string and not an array.
Any ideas what I need to do or am doing wrong? I hope it simple and I feel stupid if I get an answer...
Glad you have something that works, but if you're passing text to ExtendScript, why not format it on the AS side to be ExtendScript-friendly, like ['firstvalue', 'secondvalue', 'thirdvalue"'] --but this would be a string in AS, like
--in AS:
"['firstvalue', 'secondvalue', 'thirdvalue"']"
Then, in ExtendScript, if that's in a variable, like, myData, you can do (as I just did in ExtendScript Toolkit):
//in JS:
myArray = eval(myData);
I know using eval() is evil in web work, but for ExtendScript stuff, it can be very useful.
I hate finding an answer after I take the time to post an elaborate question.
https://stackoverflow.com/a/14689556/1204387
var path = ((File($.fileName)).path); // this is the path of the script
// now build a path to another js file
// e.g. json lib https://github.com/douglascrockford/JSON-js
var libfile = File(path +'/_libs/json2.js');
if(libfile.exists)
$.evalFile(libfile);
Like Neo learning Kung Fu, it suddenly went, "Whoa, I know JSON!"
var firstlist = JSON.parse(myresult[1]);
Gives me workable objects
doScript can pass script args to one language to another. Here is a snippet inspired from the doc:
var aps = "tell application \"Adobe InDesign CC 2014\"\
tell script args\
set user to item 1 of {\"John\", \"Mike\", \"Brenda\"}\
set value name \"user\" value user\
\"This is the firest AppleScript script argument value.\"\
end tell\
end tell"
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var user = app.scriptArgs.getValue("user");
alert( user+ "from JS" );
I don't think script args would return anything else than strings even if those could represent any kind of value. However a string can be easily turned into an array with a split method like this :
var aps = "set ls to {\"john\", \"mark\"}\
set n to count of items of ls\
set str to \"\"\
repeat with i from 1 to n\
set str to str & item i of ls\
if i < n then\
set str to str & \",\"\
end if\
end repeat\
tell application \"Adobe InDesign CC 2014\"\
tell script args\
set value name \"str\" value str\
end tell\
end tell";
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var str = app.scriptArgs.getValue("str");
var arr = str.split(",");
alert( "Item 1 of APS list is \""+arr[0]+ "\" in the JS context" );
The idea is to flatten the APS list into a comma separated string that will be later splitted in the javascript context to turn it into an array.

Find specific results from a text file

Suppose you were reading a text file, with Javascript and jQuery and suppose the server-side guy was unwilling to give you say xml or JSON, and you want to parse the thing once to get relevant text that you will use later in an autocomplete, like so:
Text file (assume there are many similar listings and there are different DATABASES):
QUERY:1
DATABASE:geoquery
NL:What are the capitals of the states that border the most populated states?
SQL:something
DR:
root(ROOT-0, What-1)
cop(What-1, are-2)
det(capitals-4, the-3)
nsubj(What-1, capitals-4)
det(states-7, the-6)
prep_of(capitals-4, states-7)
nsubj(border-9, states-7)
rcmod(states-7, border-9)
det(states-13, the-10)
advmod(populated-12, most-11)
amod(states-13, populated-12)
dobj(border-9, states-13)
QUERY:2
DATABASE:geoquery
NL:What are the capitals of states bordering New York?
SQL:SELECT state.Capital FROM state JOIN border_info ON state.State_Name
DR:
root(ROOT-0, What-1)
cop(What-1, are-2)
det(capitals-4, the-3)
nsubj(What-1, capitals-4)
prep_of(capitals-4, states-6)
partmod(states-6, bordering-7)
nn(York-9, New-8)
dobj(bordering-7, York-9)
I can use a regex to peel off say all NL: for example, but I need to first pare the file down so only specific NL's associated with a DATABASE get read. So read the file once getting all matches for a specific database that the user selects from a select, then make an array of NL from that list to be the source of an autocomplete.
$(document).ready(function(){
$.get('inputQueryExamples.txt',function(data){
// need code here to read text file first and limit results
var queryString = data;
var cleanString = "";
cleanString = queryString.match(/^NL.*/gm);
console.log(cleanString);
$('#what').html(cleanString);
var nlString = cleanString.map(function(el) {return el.replace('NL:','');});
$('#query-list').autocomplete({
source:nlString
});
});//end get
});
Thanks for any insight.
Using regex for this is like using ducktape to patch up a severed limb.
Any way,
By the looks of it, you want to get all of the NL('s) when they come from a particular database.
You would need to do a multiline regex match, with a positive lookbehind for the database name, then you'd simply match anything after NL, stopping at the next newline.
Example:
(?<=DATABASE:geoquery).*?(?<=NL:)(.*?)(?=[\r\n])
Online demo:
Regex101 Example

Replace all strings "<" and ">" in a variable with "<" and ">"

I am currently trying to code an input form where you can type and format a text for later use as XML entries. In order to make the HTML code XML-readable, I have to replace the code brackets with the corresponding symbol codes, i.e. < with < and > with >.
The formatted text gets transferred as HTML code with the variable inputtext, so we have for example the text
The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.
which needs to get converted into
The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.
I tried it with the .replace() function:
inputxml = inputxml.replace("<", "<");
inputxml = inputxml.replace(">", ">");
But this would just replace the first occurrence of the brackets. I'm pretty sure I need some sort of loop for this; I also tried using the each() function from jQuery (a friend recommended I looked at the jQuery package), but I'm still new to coding in general and I have troubles getting this to work.
How would you code a loop which would replace the code brackets within a variable as described above?
Additional information
You are, of course, right in the assumption that this is part of something larger. I am a graduate student in Japanese studies and currently, I am trying to visualize information about Japenese history in a more accessible way. For this, I am using the Simile Timeline API developed by MIT grad students. You can see a working test of a timeline on my homepage.
The Simile Timeline uses an API based on AJAX and Javascript. If you don't want to install the AJAX engine on your own server, you can implement the timeline API from the MIT. The data for the timeline is usually provided either by one or several XML files or JSON files. In my case, I use XML files; you can have a look at the XML structure in this example.
Within the timeline, there are so-called "events" on which you can click in order to reveal additional information within an info bubble popup. The text within those info bubbles originates from the XML source file. Now, if you want to do some HTML formatting within the info bubbles, you cannot use code bracket because those will just be displayed as plain text. It works if you use the symbol codes instead of the plain brackets, however.
The content for the timeline will be written by people absolutely and totally not accustomed to codified markup, i.e. historians, art historians, sociologists, among them several persons of age 50 and older. I have tried to explain to them how they have to format the XML file if they want to create a timeline, but they occasionally slip up and get frustrated when the timeline doesn't load because they forgot to close a bracket or to include an apostrophe.
In order to make it easier, I have tried making an easy-to-use input form where you can enter all the information and format the text WYSIWYG style and then have it converted into XML code which you just have to copy and paste into the XML source file. Most of it works, though I am still struggling with the conversion of the text markup in the main text field.
The conversion of the code brackets into symbol code is the last thing I needed to get working in order to have a working input form.
look here:
http://www.bradino.com/javascript/string-replace/
just use this regex to replace all:
str = str.replace(/\</g,"<") //for <
str = str.replace(/\>/g,">") //for >
To store an arbitrary string in XML, use the native XML capabilities of the browser. It will be a hell of a lot simpler that way, plus you will never have to think about the edge cases again (for example attribute values that contain quotes or pointy brackets).
A tip to think of when working with XML: Do never ever ever build XML from strings by concatenation if there is any way to avoid it. You will get yourself into trouble that way. There are APIs to handle XML, use them.
Going from your code, I would suggest the following:
$(function() {
$("#addbutton").click(function() {
var eventXml = XmlCreate("<event/>");
var $event = $(eventXml);
$event.attr("title", $("#titlefield").val());
$event.attr("start", [$("#bmonth").val(), $("#bday").val(), $("#byear").val()].join(" "));
if (parseInt($("#eyear").val()) > 0) {
$event.attr("end", [$("#emonth").val(), $("#eday").val(), $("#eyear").val()].join(" "));
$event.attr("isDuration", "true");
} else {
$event.attr("isDuration", "false");
}
$event.text( tinyMCE.activeEditor.getContent() );
$("#outputtext").val( XmlSerialize(eventXml) );
});
});
// helper function to create an XML DOM Document
function XmlCreate(xmlString) {
var x;
if (typeof DOMParser === "function") {
var p = new DOMParser();
x = p.parseFromString(xmlString,"text/xml");
} else {
x = new ActiveXObject("Microsoft.XMLDOM");
x.async = false;
x.loadXML(xmlString);
}
return x.documentElement;
}
// helper function to turn an XML DOM Document into a string
function XmlSerialize(xml) {
var s;
if (typeof XMLSerializer === "function") {
var x = new XMLSerializer();
s = x.serializeToString(xml);
} else {
s = xml.xml;
}
return s
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
You might use a regular expression with the "g" (global match) flag.
var entities = {'<': '<', '>': '>'};
'<inputtext><anotherinputext>'.replace(
/[<>]/g, function (s) {
return entities[s];
}
);
You could also surround your XML entries with the following:
<![CDATA[...]]>
See example:
<xml>
<tag><![CDATA[The <b>Genji</b> and the <b>Heike</b> waged a long and bloody war.]]></tag>
</xml>
Wikipedia Article:
http://en.wikipedia.org/wiki/CDATA
What you really need, as mentioned in comments, is to XML-encode the string. If you absolutely want to do this is Javascript, have a look at the PHP.js function htmlentities.
I created a simple JS function to replace Greater Than and Less Than characters
Here is an example dirty string: < noreply#email.com >
Here is an example cleaned string: [ noreply#email.com ]
function RemoveGLthanChar(notes) {
var regex = /<[^>](.*?)>/g;
var strBlocks = notes.match(regex);
strBlocks.forEach(function (dirtyBlock) {
let cleanBlock = dirtyBlock.replace("<", "[").replace(">", "]");
notes = notes.replace(dirtyBlock, cleanBlock);
});
return notes;
}
Call it using
$('#form1').submit(function (e) {
e.preventDefault();
var dirtyBlock = $("#comments").val();
var cleanedBlock = RemoveGLthanChar(dirtyBlock);
$("#comments").val(cleanedBlock);
this.submit();
});

Categories

Resources