Find and Extract Text in DOM - javascript

I am looking to extract a piece of text from the DOM. The data I am interested in is "1234567"
<script type="text/javascript">
function example() {
launchChat("ABC", "1234567", "Sample Data", "Customer");
}
</script>
So far this is what I have got -
$("head").find("script").each(function(i) {
var scr = $(this).html();
var regExp = /launchChat(([^)]+))/; //Outputs everything in between the brackets
var matches = scr.match(regex);
console.log("match " +matches);
});
Any help is much appreciated.

Ok if it helps anyone at some point in the future, the answer is -
$("head").find("script").each(function(i) {
var scr = $(this).html();
if(scr.indexOf("launchChat") > 0){
var newTxt = scr.split('"');
for (var i = 1; i < newTxt.length; i++) {
console.log(newTxt[i].split('"')[3]);
}
}
});

Related

Auto link a phrase on a page using javascript

The code below is meant to put links in words, but it works with only one word, I would like it to work with two words or more
Example:
"contact us": "www.example.com/contact.html",
"need help": "www.example.com/help.html",
"quick-thinking": "www.example.com/quick.html",
The code:
document.addEventListener("DOMContentLoaded", function(){
var links = {
"contact": "www.example.com/contact.html",
"help": "www.example.com/help.html",
}
var bodi = document.querySelectorAll("body *:not(script)");
for(var x=0; x<bodi.length; x++){
var html = bodi[x].innerHTML;
for(var i in links){
var re = new RegExp("([\\s| ]"+i+"(?:(?=[,<.\\s])))", "gi");
var matches = html.match(re);
if(matches){
matches = html.match(re)[0].trim();
html = html.replace(re, function(a){
return ' '+a.match(/[A-zÀ-ú]+/)[0].trim()+'';
});
}
}
bodi[x].innerHTML = html;
}
});
<div>
Please contact us if you need help
</div>
Update:
I'm not sure if this part is working, but I want you to not change words from script, img and class="thisclass" or .thisclass:
document.querySelectorAll("body *:not(script)")
You were just replacing it wrong.
a.match(/[A-zÀ-ú]...
needs to allow for a space character
a.match(/[A-zÀ-ú\s]...
See below:
document.addEventListener("DOMContentLoaded", function(){
var links = {
"contact us": "www.example.com/contact.html",
"need help": "www.example.com/help.html",
"hyphen-spaced-word" : "www.example.com/help.html"
}
var bodi = document.querySelectorAll("body *:not(script)");
for(var x=0; x<bodi.length; x++){
var html = bodi[x].innerHTML;
for(var i in links){
var re = new RegExp("([\\s| ]"+i+"(?:(?=[,<.\\s])))", "gi");
var matches = html.match(re);
//console.log(matches);
if(matches){
matches = html.match(re)[0].trim();
html = html.replace(re, function(a){
return ' '+a.match(/[A-zÀ-ú\s-]+/)[0].trim()+'';
});
}
}
bodi[x].innerHTML = html;
}
});
<div>
Please contact us if you need help. See hyphen-spaced-word.
</div>

Javascript: How do I prevent reappending a string to multiple queries?

In this case, lets take YouTube as an example:
The below code, I believe, is scripted to append a string to search_query=, but it gets appended to &page= as well.
if (oSession.uriContains("www.youtube.com/results?search_query="))
{
var str = oSession.fullUrl;
var sAppend = "+test1+test2+test3";
if (oSession.fullUrl.indexOf(sAppend, str.length - sAppend.length) < 0)
{
oSession.fullUrl = str + sAppend;
}
}
Thank you in advance.
You can try this code:
if (oSession.uriContains("www.youtube.com/results?search_query="))
{
var str = oSession.fullUrl;
var sAppend = "+test1+test2+test3";
if (!oSession.uriContains(sAppend))
{
oSession.fullUrl = str + sAppend;
}
}

Scroll text method, works with arrays, not with string

Basic javascript function to scroll the text in the title bar, I'm calling it via a setInterval("rotateTitle()", 1000); call after onload.
This function, which takes text from an array, works perfectly.
var counter = 0;
function rotateTitle() {
var baseTitle = "www.mydomain.com - now with JavaScript";
var titleArray = new Array("a","b","c","d","e","f","g");
var titleString = "abcdefg";
var scrollText = getNextScroll(titleArray);
window.document.title=baseTitle.concat(scrollText);
}
function getNextScroll(inValue) {
var str = " ";
for (var i = 0; i<inValue.length; i++) {
var index = i+counter;
if (i+counter >= inValue.length) {
index -= inValue.length;
}
str += inValue[index];
}
counter++;
if (counter > inValue.length) {
counter = 0;
}
return str;
}
Edited here for clarity:
Now if I rewrite the function to scroll a string (not an array), I change the line
str += inValue[index];
to
str.concat(inValue.charAt(index));
and change getNextScroll(titleArray) to getNextScroll(titleString), the script seems to execute, but only the baseTitle is shown.
Why is this wrong?
You have to assign the result of str.concat back to str; otherwise you'll miss the concat operation. Instead of charAt you must use inValue[index].
Do like this:
str = str.concat(inValue[index]);
Here's a JS Bin: http://jsbin.com/aCEBAju/2/
In your original code you have this:
str.concat(inValue.charAt(index));
debugging in Chrome it barks: array has no method charAt.
The solution to the problem is that str.concat(inValue.charAt(index)); must change to str = str.concat(inValue.charAt(index)); or str += inValue.charAt(index);. Str must be assigned the new value. This is the entire working function:
var counter = 0;
function rotateTitle() {
var baseTitle = "www.berrmal.com - now with JavaScript";
var titleArray = new Array("b","e","r","r","m","a","l"); //no longer necessary
var titleString = "berrmal: bigger, longer, uncut";
var scrollText = getNextScroll(titleString);
window.document.title=baseTitle.concat(scrollText);
}
function getNextScroll(inString) {
var str = " ";
for (var i = 0; i<inString.length; i++) {
var index = i+counter;
if (i+counter >= inString.length) {
index -= inString.length;
}
str += inString.charAt(index);
}
counter++;
if (counter > inString.length) {
counter = 0;
}
return str;
}
I figured out the answer to the problem based on Leniel Macaferi's answer, though his posted code is not correct. This method runs successfully in Firefox 23.0 with no error in the console.

Google Apps Script: How to find a listItem object in a google document and insert a item to it?

Following the documentation sample, I'm trying to create a function that searchs for a numerated list in a google document and, if finds it, adds a new item to that list. But I get this error: Cannot find method setListId(string). (line 21, file "test") or, if I change line 21 content (replacing elementContentfor newElement), I get the message: Preparing for execution... and nothing happens. How to fix it?
This is my code:
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = "1R2c3vo9oOOjjlDR_n5L6Tf9yb-luzt4IxpHwwZoTeLE";
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
var listId = child.getListId();
var newElement = body.appendListItem(elementContent);
newElement.setListId(newElement);
Logger.log("child = " + child);
}
}
}
Following my comment, I tried to play with your script to see what happened and I came up with that code below...
I'm not saying it solves your issue and/or is the best way to achieve what you want but at least it gives a result that works as expected.
Please consider it as a "new playground" and keep experimenting on it to make it better ;-)
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = DocumentApp.getActiveDocument().getId();
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
var childIndex = 0;
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
child = targetDoc.getChild(i)
childIndex = body.getChildIndex(child);
Logger.log(childIndex)
i++
}
child = targetDoc.getChild(i-2)
var listId = child.getListId();
Logger.log(childIndex)
var newElement = child.getParent().insertListItem(childIndex, elementContent);
newElement.setListId(child);
break;
}
}
}

Cannot make two simple JS code to work at the same time

I've basic knowledge of JS. I'm trying to make the two functions below to work together but I cannot find a solution. It's either one or the other that work but not the two together.
<script>
function random_string(size){
var str = "";
for (var i = 0; i < size; i++){
str += random_character();
}
return str;
}
function random_character() {
var chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
return chars.substr( Math.floor(Math.random() * 62), 1);
}
window.onload = function () {
var partnerurl = document.getElementById('field1');
uniqueid = document.getElementById('field2');
uniqueid.value = random_string(15);
partnerurl.value = "www.website.com"+uniqueid.value
};
</script>
<script>
var defaultHiddenFieldNameValue = "";
function getQueryStringParamValue(strQStrParam) {
var strURL = document.location.href;
var strQStrParamValue = "";
if (strURL.indexOf('?') != -1)
{
strQStrParamValue = strURL.substr(strURL.indexOf('?') + 1);
if (strQStrParamValue.indexOf(strQStrParam) != -1)
{
strQStrParamValue = strQStrParamValue.substr(strQStrParamValue.indexOf(strQStrParam));
strQStrParamValue = strQStrParamValue.substr(strQStrParamValue.indexOf('=') + 1);
if (strQStrParamValue.indexOf('&') != -1)
strQStrParamValue = strQStrParamValue.substr(0, strQStrParamValue.indexOf('&'));
return strQStrParamValue;
}else{
strQStrParamValue = defaultHiddenFieldNameValue;
return strQStrParamValue;
}
}else{
strQStrParamValue = defaultHiddenFieldNameValue;
return strQStrParamValue;
}
}
// Form name goes here
var form = "formname";
function setCampaign(){
var elqForm = document.forms[form];
//repeat for each field to populate
elqForm.elements['src'].value = getQueryStringParamValue('src');
}
window.onload = setCampaign;
</script>
Many thanks in advance for your help!
Cheers,
FX
In your code sample here you are missing a semicolon on the last line of the onload function.
I also don't see you declaring uniqueid.
Your random string function works fine, its just getting the window.onload to fire that I had problems with.
Here is a demostration of your random string working fine: http://jsfiddle.net/Jimmery/tv87X/
I would suggest loading jQuery with this line in your HTML:
<script src="ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
and then use this:
$(document).ready(function(){
var partnerurl = $('field1');
var uniqueid = $('field2');
uniqueid.val(random_string(15));
partnerurl.val("www.website.com/"+uniqueid.val());
};

Categories