Prompt user to replace certain parts of text in a string - javascript

I have a program that allows a user to type JavaScript in a textbox, and it executes in an HTML viewer or iframe. There is a drop down with options such as "Insert Image", which inserts
var $'Image Name' = document.createElement('img');
$'Image Name'.src = $'Image URL';
$'Image Name'.style.position = 'absolute';
document.body.appendChild($'Image Name');
into the textbox. I want the user to select the option "Insert Image", and have a dialog go through each $'', and ask for something to replace them with, so for the first $'Image Name', prompt the user for a variable name, and then replace("$'Image Name'", userText) so all the $'Image Name's get replaced and the user isn't prompted for the same one again. Any ideas? I have this replace:
replace(/^\$\"|\'.$\"|\'/gi, function ($string) { return prompt($string);});
but it matches the quotes, not the text inside the quotes, and I don't even know regex, if you can solve the regex, I can figure out the rest.

I guess you want something like this:
replace(/\$'([^']+)'/g, function (s, contents) { return prompt(contents); });
though I should mention that this will misbehave if a single-quoted string happens to end with a dollar-sign, or if a double-quoted string happens to contain $', or whatnot; do you need to be able to handle these sorts of cases? (It's not obvious from your question whether you completely control the contents of the textarea, or whether it's something your users might be editing.)

Related

How can I print Jquery output to a field that saves on form submission?

I'm using the following code to output the wordcount of an array, separated by ", " (comma and a space) and count the amount of words:
jQuery(document).ready(function($){
$('#field_d9kag').change(function(){
var s = this.value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("frm_field_104_container").innerHTML = (s.split(', ').length);
});
});
The ('#field_d9kag') just relates to another field that holds the array. What the script sees is, for example:
One, Two, Three
This actually works great and gives the correct wordcount number. Although the number shows, it can't actually be used in the way needed. My aim is to place it in the field ("frm_field_104_container") and save it as a form entry, but it currently can't be saved to the database on form submission by this method. Instead it acts more as document.write or console.log. Great for seeing what's what, but not fit for the pupose needed.
Can anyone point me in the direction of how to make the count a saveable entry/input within a form field?

Regex for finding link

I have an issue related to finding a regex for the link with some conditions. Here is the scenario:
I have created utils.ts it's a typescript. basically, it will take an API response as an input and return the formatted HTML supported text, like bold text, email, Images, Links.
So let's take one scenario which I am facing.
as a return of the utils.ts file, I am getting this.
https://www.google.com Click here
(Note: normal links and 'a' tag links can occure in any order)
from the above text, as you can see this part Click here is already in HTML supported method.
So I will get the following output on GUI
https://www.google.com Click here
so from this point, I want a regex which can format https://www.google.com but it must not manipulate Click here as it is already formated.
Here I also want to format https:///www.google.com as follow
Google
The main problem I am facing is when I am replacing the string with 'https://..' with tags it will also replace the links inside 'href' like this
Google Google">Click me</a>
Which is what I don't want.
Please share your thought on this.
Thank you
Not yet formatted links can be found using alternations. The idea is - if a link is formatted it's not captured to a group (don't be confused that the regex still finds something - you should only look at Group 1). Otherwise, the link is captured to a group.
The regex below is really simple, just to explain the idea. You might want to update it with a better URL search pattern.
demo
(?:href="https?\S+")|(https?\S+)
If I understood correctly, you want to extract from the text those web addresses that appear in the text and are not links. If so check out the following javascript:
//the data:
var txt1='https://www.google.com Click here http://other.domain.com';
// strip html tags
String.prototype.stripHTML = function () {
var reTag = /<(?:.|\s)*?>/g;
return this.replace(reTag, " ");
};
var txt2=txt1.stripHTML();
//console.log(txt2);
//split tokens
var regex1 = /\s/;
var tokens = txt2.split(regex1);
//console.log(tokens);
//build an address table
regex2=/^https?:\/\/.*/;
var i=0, j=0;
var addresses=[];
for (i in tokens) {
if (regex2.test(tokens[i])) {
addresses[j] = tokens[i];
j++;
}
i++;
}
console.log(addresses);

How to populate text fields with data in one subform to another subform from a dropdown list in LiveCycle

I don't know much about JavaScript but feel that this should be fairly easy. I have a drop down list with several options and the below is under the 'Click' option:
form1.CapExForm.Subform1.Table1.HeaderRow[0].DropDownList1::click - (JavaScript, client)
I would like to type in someone's name populate in a text field that has the header scrip below:
form1.Subform3.ApprovalSubForm.Table3.Row2.RequestorName::click - (JavaScript, client)
I had previously done this in a PDF form but needed the form to flow and add rows so moved to LiveCycle. Below is the script ("Software >$1,000,000" was from the dropdown list and all information below that would be the textfields I'm wanting to populate based off that selection) I had in Adobe PDF form if that helps clarify what I am attempting:
if (event.value=="Software >$1,000,000") {
this.getField("Name").value = "Type Requestor Name";
this.getField("Name_2").value = "Type Dept. Manager";
this.getField("Name_3").value = "Todd Stephenson";
this.getField("Name_4").value = "John Kapchinske";
this.getField("Name_5").value = "N/A";
this.getField("Text2").value = "Approval Reviewed: Hazel Welch";
this.getField("Signature").value = "Must click, sign, and save to add signature";
this.getField("Signature_2").value = "Must click, sign, and save to add signature";
this.getField("Signature_3").value = "Must click, sign, and save to add signature";
this.getField("Signature_4").value = "Must click, sign, and save to add signature";
this.getField("Signature_5").value = "Must click, sign, and save to add signature";
this.getField("Signature1").value = "Must click, sign, and save to add signature";
}
Ok - I'm not sure I understand what you want to do, but I'm giving it my best guess. You want some other fields to populate when you select a value from the dropdown, correct?
The javascript for Designer works differently than that for Acrobat. Here is a good reference for that:
Livecycle Scripting Reference.
And here is a more comprehensive list of the properties available through javascript in Designer.
First, put it in the change event for the dropdown. If you put it in the click event it'll run whenever they click on the field, even if they don't make a change.
In that event, put javascript like this:
if (xfa.event.newText == "Software >$1,000,000")
{
field1SOMexpression.rawValue = "Value you want";
field2SOMexpression.rawValue = "Next value you want";
//add the other fields you want to reference here
}
Here, xfa.event.newText refers to the value of the dropdown after the change. The property .newText is only available during a change event, and you want to use that one because during the change event, the rawValue of that field is whatever the original value was. The rest of the time you would want to use .rawValue to access the value of a field, and that's why we are using it to set the value of the other fields (because they aren't the fields that triggered the change event.)
A SOM expression is a reference to a field. Example - based on what you pasted above, the SOM expression for the dropdown is form1.CapExForm.Subform1.Table1.HeaderRow[0].DropDownList1.
Without seeing the form I can't tell you what the expression for the fields you want to set values would be, but there are a couple of ways to get the field expression for each field you want to set. The simplest way is to go to the script editor, hold the control and shift keys, and click on the field; this inserts its SOM expression into the script window.
EDIT: If you want the value to be based on the combo of two fields, then it might be easier to use a calculate script in the field that needs to change.
Put script into the calculate event for the field whose value you want to set, to decide what its value should be based on the values of the two dropdowns.
It should be something like this:
var myValue = "";
var type = form1.CapExForm.Subform1.Table1.HeaderRow[0].DropDownList1.rawValue;
var price = ....(whatever the som expression is).PriceRange.rawValue;
if (type == "Software" && price == "1,000,000")
{
myValue = "Value you want";
}
else if (type == "Something else" && price == "Some other price . .")
{
myValue = "Some other value");
}
this.rawValue = myValue;
In that case, 'this' would refer to the field that you want to change the value on, since the script would be running in that field's calculate event. The calculate event fires whenever something changes in one of the fields that are referenced in the calculate script.

How to detect Links with out anchor element in a plain text

If user enters his text in the text box and saves it and again what's to add some more text he can edit that text and save it if required.
Firstly if user enters that text with some links I, detected them and converted any hyperlinks to linkify in new tab. Secondly if user wants to add some more text and links he clicks on edit and add them and save it at this time I must ignore the links that already hyperlinked with anchor button
Please help and advice
For example:
what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/ for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br>http://www.stackoverflow.com/<br> <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg<br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>
Test URL's
http://www.stackoverflow.com/
http://stackoverflow.com/
https://stackoverflow.com/
www.stackoverflow.com
//stackoverflow.com/
<a href='http://stackoverflow.com/'>http://stackoverflow.com/</a>";
I've tried this code
function Linkify(what) {
str = what; out = ""; url = ""; i = 0;
do {
url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i);
if(url!=null) {
// get href value
href = url[0];
if(href.substr(0,7)!="http://") href = "http://"+href;
// where the match occured
where = str.indexOf(url[0]);
// add it to the output
out += str.substr(0,where);
// link it
out += ''+url[0]+'';
// prepare str for next round
str = str.substr((where+url[0].length));
} else {
out += str;
str = "";
}
} while(str.length>0);
return out;
}
Please help
Thanks.
here is a regex where you select all the links without having anchors
(?:(?:http(?:s)?(?:\:\/\/))?(?:www\.)?(?:\w)*(?:\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))
Here is a RegExFiddle (updated 14:41)
quit a lil difficult task because in javascript you don't have a preceded by statement. :)
EDIT1: Now it detects...
http://www.abc.xy
http://abc.xy
https://www.abc.xy
https://abc.xy
www.abc.xy
abc.xy
EDIT2:
Here is it a little shorted and the usage fiddle
Regex
/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g
function
function Linkify(str) {
var newStr = str.replace(/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g,'$1');
return newStr;
}
var newData = Linkify(data);
WORKING JS-FIDDLE
EDIT 1.000.000 :D
/((http(s)?(\:\/\/))?(www\.)?([\w\-\.\/])*(\.[a-zA-Z]{2,3}\/?))(?!(.*a>)|(\'|\"))/g
this solves your problem now.
the only problem you will run in here is, 4 letters after a dot is not selected. e.g .info if you want them selected than change {2,3} to {2,4} BUT be carefully... if someone adds a text like my name is.john than is.john will be translated to a link.
EDIT 2.0
If you have a really complex URL like the following
((http(s)?(\:\/\/))?(www\.)?([\a-zA-Z0-9-_\.\/])*(\.[a-zA-Z]{2,3}\/?))([\a-zA-Z0-9-_\/?=&#])*(?!(.*a>)|(\'|\"))
Matches
https://stackoverflow.com/questions/34170950/summernote-inserthtml?firstname=channaveer&lastname=hakari#fsdfsdf
A more simple solution is probably to strip the links which you created (so the user gets exactly what they typed when they click "Edit" again).
Another idea is to split the string at </a>. That gives you a list of strings which all end with an anchor element (except the last one). Iterate over this list, cut away the part after the last <a, linkify.

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

Categories

Resources