Replacing tag content with html string - node.js

I have the following xml:
<foo><toReplace/></foo>
I want to replace <toReplace/> tag with the following string:
"<b>bar</b>"
How can I do that?
Right now I have the following code:
var xml = "<foo><toReplace/></foo>";
var parser = new dom.DOMParser().parseFromString(xml, "text/xml");
parser.getElementsByTagName("toReplacce")[0].textNode = "<b>bar</b>";
console.log(parser.toString()); // "<foo><b>bar</b>"
The problem is that is escapes HTML. How can I replace the content with the HTML string here?

you can always use the module from npm
var unescape = require('unescape');
console.log(unescape(parser.toString()))
When I tested your code there is a small typo: (toReplacce instead of toReplace)
var dom = require('xmldom');
var xml = "<foo><toReplace/></foo>";
var parser = new dom.DOMParser().parseFromString(xml, "text/xml");
var a = parser.getElementsByTagName("toReplace")[0];
//console.dir(a);
a.textvalue = "<b>bar</b>";
console.log(parser.toString());

Related

Convert Specific String to JSON Object

const test ="[{contactId=2525, additionDetail=samle}]";
I need to convert this string to a JSON object. It will dynamically load like this string. I need to particular string to convert to a JSON object.
JSON.parse(test) command not working for this. I attached the error here.
For that specific string, you'd have to parse it yourself.
const test = '[{contactId=2525, additionDetail=samle}]';
const obj = {};
test.split(/[{}]/)[1].split(/, /).forEach((elm) => {
const entry = elm.split('=');
obj[entry[0]] = entry[1];
});
What I am doing is splitting the string on the braces and selecting the second element (utilising regex) then splitting that on comma and space (again regex) then loop over the result and assign to an object.
You can then JSON.stringify(obj) for the result.
:edit:
For the second string you've asked for there is another, potentially more refined, answer. You'll need to first replace the = with : (I've again used a regex), then you use a regex to match the words and sentence and use a function to add the quotes.
const test = '[{contactId=2525, additionDetail=samle}]';
const test2 = "[{contactId=2525, additionDetail=rrr additional Detail, medicationType={medicationTypeId=3333, medicationType=Tablet}, endDate=2022-12-30}]";
const replaced = test.replace(/=/g,':')
const replaced2 = test2.replace(/=/g, ':');
const replacer = function(match){
return '"' + match + '"';
}
const replacedQuote = replaced.replace(/(?!\s)[-?\w ?]+/g,replacer);
const replaced2Quote = replaced2.replace(/(?!\s)[-?\w ?]+/g,replacer);
const obj = JSON.parse(replacedQuote);
const obj2 = JSON.parse(replaced2Quote);
You should note that Json means javascript object notation, so you need to create a JavaScript object to get started:
const test ="[{contactId=2525, additionDetail=samle}]";
let obj = Object.create(null)
You can now define your variable as one of the object properties :
obj.test = test
Now we have a JavaScript object and we can convert it to json:
let convertedToJson = JSON.stringify(test);
[{contactId=2525, additionDetail=samle}]
this is not a valid JSON-string, and it cannot be parsed by JSON.parse()
the correct JSON-string would be:
const test ='[{"contactId":2525, "additionDetail":"samle"}]';

Is there a way to replace several occurences in a HTML file in one line?

Please can you tell me how to make shorter this code. i wanna do it in one line.
var htmlstring = "{{1}}Hello {{2}}, clic here !";
var firststep = htmlstring.replace('{{1}}', "http://google.fr");
var secondstep = htmlstring.replace('{{1}}', "http://google.fr");
var thirdstep = secondstep.replacee('{{2}}', "Mister");
In short,
I have it:
{{1}}Hello {{2}}, clic here !
I wanna have this at the end:
http://google.frHello Mister, clic here !"
Sure, use String.replace and regexp:
const html = '{{1}}Hello {{2}}, click here !'
const url = 'http://google.fr';
const name = 'Mister';
const output = html.replace(/\{\{1\}\}/g, url).replace(/\{\{2\}\}/g, name);
I have no Idea how you can replace both {{1}} and {{2}} in one go, but you can replace both occurences of {{1}} by using this function:
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
Use it like this:
var htmlstring = '{{1}}Hello {{2}}, clic here !';
htmlstring.replaceAll("{{1}}", "http://google.fr");
htmlstring.replaceAll("{{2}}", "Mister");
ES6 Update:
You can now use an even better function for the replaceAll() method:
String.prototype.replaceAll = function(search, replacement) {
return this.split(search).join(replacement);
};
This will utilize .split() to first make an array without the search value and then .join() that Array with the replacement:
String.prototype.replaceAll = function(search, replacement) {return this.split(search).join(replacement);};
let htmlstring = `{{1}}Hello {{2}}, click here !`;
console.log(htmlstring.replaceAll("{{1}}","https://google.fr").replaceAll("{{2}}", "Mister"));

SharePoint JSOM Parsing values in a hyperlink field

I have a value that looks like "mailto:a#b.com, mailto:a#b.com'. This is basically a hyperlink field and I want to parse this properly using SharePoint JSOM. I tried SP.FieldUrlValue, but it does not seem to have a method that lets you parse.
You can use the .get_url() function on the actual item value to get the hyperlink URL, or the .get_description() function to get the hyperlink's display text.
var linkField = "internalColumnName";
var listName = "List Title";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var camlQuery = new SP.CamlQuery();
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
var itemEnumerator = items.getEnumerator();
while(itemEnumerator.moveNext()){
var item = itemEnumerator.get_current();
var url = item.get_item(linkField).get_url(); // <-- Get URL
var text = item.get_item(linkField).get_description(); // <-- Get Text
alert(url + ", " + text);
}
}),Function.createDelegate(this,function(sender, args){alert(args.get_message());}));

NotesRichTextItem.getMIMEEntity() always returns null

I have a notes form with a rich text field on it, called "Body". I've set the "Storage" property of the field to "Store contents as HTML and MIME".
Now, I am creating a new document with that form in the Notes Client.
However, if I try to access the rich text field's value in SSJS with NotesRichTextItem.getMIMEEntity(), it always returns null.
Am I missing something?
Thank you for your help in advance.
Update 2: 02/12/2015
I did some more testing and I found the cause, why it won't recognize the rich text field as MIME Type, but rather always returns it as RICH TEXT:
The cause is me accessing the database with "sessionAsSigner" rather than just using "database".
If I remove "sessionAsSigner" and use "database" instead, making the XPage unavailable to public access users, so, I am forced to log in, the code recognizes it as MIME Type and I can get a handle on NotesMIMEEntity.
Unfortunately, the XPage has to be available to public access users and I have to use sessionAsSigner.
When I open the document properties and I look at the rich text field, I can see that the "Field Flags" are "SIGN SEAL". My guess is, that's why sessionAsSigner doesn't work, but it is just a guess.
Any ideas?
Update 1: 02/12/2015
Here is the code I am using in my SSJS:
var oDBCurrent:NotesDatabase = sessionAsSigner.getDatabase(session.getServerName(), session.getCurrentDatabase().getFilePath());
var oVWMailProfiles:NotesView = oDBCurrent.getView('$vwSYSLookupEmailProfiles');
var oVWPWResetRecipient:NotesView = oDBCurrent.getView('$vwPWPMLookupPWResetNotificationProfiles');
var oDocPWResetRecipient:NotesDocument = null;
var oDocMailProfile:NotesDocument = null;
var oDocMail:NotesDocument = null;
var sServer = session.getServerName();
oDocPWResetRecipient = oVWPWResetRecipient.getDocumentByKey(sServer, true);
oDocMailProfile = oVWMailProfiles.getDocumentByKey('.MailTemplate', true);
oDocMail = oDBCurrent.createDocument();
//Set default fields
oDocMail.replaceItemValue('Form', 'Memo');
oDocMail.replaceItemValue('Subject', oDocMailProfile.getItemValueString('iTxtSubject'));
oDocMail.replaceItemValue('SendTo', oDocPWResetRecipient.getItemValue('iNmesRecipients'))
//Get body text
var oItem:NotesItem = oDocMailProfile.getFirstItem("Body");
var entity:NotesMIMEEntity = oItem.getMIMEEntity();
//Create email body
var tmp = entity.getContentAsText();
//Replace <part2> with part 2 of the password
tmp = #ReplaceSubstring(tmp, "<part2>", sPWPart2);
//Set content of Body field as MIME type
var body = oDocMail.createMIMEEntity();
var stream = session.createStream();
stream.writeText(tmp);
body.setContentFromText(stream, "text/html; charset=iso-8859-1", 0);
//Send email
oDocMail.send();
As I mentioned before, I've also tried:
var oDBCurrent:NotesDatabase = sessionAsSigner.getDatabase(session.getServerName(), session.getCurrentDatabase().getFilePath());
var oVWMailProfiles:NotesView = oDBCurrent.getView('$vwSYSLookupEmailProfiles');
var oVWPWResetRecipient:NotesView = oDBCurrent.getView('$vwPWPMLookupPWResetNotificationProfiles');
var oDocPWResetRecipient:NotesDocument = null;
var oDocMailProfile:NotesDocument = null;
var oDocMail:NotesDocument = null;
var sServer = session.getServerName();
oDocPWResetRecipient = oVWPWResetRecipient.getDocumentByKey(sServer, true);
oDocMailProfile = oVWMailProfiles.getDocumentByKey('.MailTemplate', true);
oDocMail = oDBCurrent.createDocument();
//Set default fields
oDocMail.replaceItemValue('Form', 'Memo');
oDocMail.replaceItemValue('Subject', oDocMailProfile.getItemValueString('iTxtSubject'));
oDocMail.replaceItemValue('SendTo', oDocPWResetRecipient.getItemValue('iNmesRecipients'))
//Get body text
var entity:NotesMIMEEntity = oDocMailProfile.getMIMEEntity('Body');
//Create email body
var tmp = entity.getContentAsText();
//Replace <part2> with part 2 of the password
tmp = #ReplaceSubstring(tmp, "<part2>", sPWPart2);
//Set content of Body field as MIME type
var body = oDocMail.createMIMEEntity();
var stream = session.createStream();
stream.writeText(tmp);
body.setContentFromText(stream, "text/html; charset=iso-8859-1", 0);
//Send email
oDocMail.send();
Try calling sessionAsSigner.setConvertMime(false)
You get the MIMEEntity from the document, not from the Richtext item. See an example here (starting at line 103): https://github.com/zeromancer1972/OSnippets/blob/master/CustomControls/ccSnippets.xsp
You should set the session to not convert MIME to RichText.
Add this at the start of your code.
session.setConvertMime(false);

ITextSharp: parse html with cyrillic/international words

I try to parse html file and to generate pdf. I use code
document.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
IPipeline pipeline =
new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext,
new PdfWriterPipeline(document, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(true, worker, Encoding.Unicode);
p.Parse((TextReader)File.OpenText(#"Template.html"));
document.Close();
How can I define base font, If i'd like use cyrillic/international words?
You should register font
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
FontFactory.Register(arialuniTff);
and modifed page's body
<body face='Arial' encoding='koi8-r' >
...
</body >
For somebody, who can read in russian, this article can be useful
I propose the following variant
//connect the font
String FONT_LOCATION = Server.MapPath("~/fonts/arial.ttf");
BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
//connected
PdfPCell cell1 = new PdfPCell(new Phrase(lblN, font)) { HorizontalAlignment = 1, VerticalAlignment= 1 };

Resources