javascript- replace text with part of the file name - javascript

I'm trying to create a script in adobe illustrator that will check if a file name contains "ph" +5 numbers.
If it has been found then it will replace a part of a text with the match from the file name.
This is what I have so far I just can't get it to work, the text is replaced with "null"
var doc = app.activeDocument;
var name = doc.name;
var match = name.match(/ph\d{5}/);
for (i = 0; i < doc.textFrames.length; i++)
{
doc.textFrames[i].contents = doc.textFrames[i].contents.replace(/ph00000/gi, match);
}

I'd try this:
var doc = app.activeDocument;
var match = doc.name.match(/ph\d{5}/);
if (match != null) {
for (i = 0; i < doc.textFrames.length; i++) {
doc.textFrames[i].contents = doc.textFrames[i].contents.replace(/ph00000/gi, match[0]);
}
}

You can encapsulate the text that you want to replace with group constructs, and since you're using String.prototype.replace, you can capture the parenthesized group and pass the callback function as the 2nd argument in your .replace function.
Read more about it here
Example:
const textString = "This is ph54321 or ph12345";
const newString1 = textString.replace(/(ph)\d{5}/gi, function (matches, p1) {
return p1 + "appended"; // "This is phappended or phappended"
});
const newString2 = textString.replace(/ph(\d{5})/gi, function (matches, p1) {
return "BIGPH" + p1; // "This is BIGPH54321 or BIGPH12345"
});
console.log({newString1});
console.log({newString2});

Related

Highlight words from string started with #

There is a string that may contain nicknames given by #nickname. Nickname can be inputed by user with typo by concatenation with previous word, like
Hello my inst is#nickname
Also nickname word can be situated at the beginning of the new paragraph, hence just using split(' ') wouldn’t work.
What I want ultimately do is to after user inputs, highlight nicknames in string by covering them with <span> setting some styles and adding onclick link to instagram with that account.
Solution I’ve made so far:
<script>
window.onload=function()
{
var text = "Hello #buf world #text";
text = Synt(text);
var a = addP(document.body,text,30,30,"black",20);
a.innerHTML=text;
}
function Synt(a)
{
if(a.search('#')==-1)
return a;
else
{
var regex = /#/gi, result, indices = [];
while ( (result = regex.exec(a)) ) {
indices.push(result.index);
}
var a1 = (' ' + a).slice(1);
var ar = a.split('');
for(var i=0;i<indices.length;i++)
{
var r=[];
var rr=0;
for(var j=indices[i];j<a.length&&(isLetter(a[j])||a[j]=='.'||a[j]=='_'||rr==0);rr++,j++)
r[rr]=a[j];
r=r.join('');
a1 = a1.replace(r,'<span style="color:blue">'+r+'</span>');
}
return a1;
}
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z|0-9]/i);
}
function addP(par,text,left,top,color='black',size='17px', fun=0)
{
var p = document.createElement('p');
p.style.position = 'absolute';
p.style.color=color
p.style.fontSize=size;
p.style.fontFamily='Arial';
par.appendChild(p);
p.style.left=left;
p.style.top=top;
p.innerText=text;
if(fun)
p.onclick=fun;
return p;
}
</script>

Javascript spilt function does not recognise one of the tabs in my string

I have a string with tab-separated data copied from Excel. The javascript split does not recognise the 2nd tab in the string. I have pasted the string into notepad++ to see the tabs and they are all there. Exploding the string in PHP works fine. The test code is:
function testTab(str) {
var strSplit = str.split('\t');
for (i=0; i < strSplit.length; i++){
console.log('strSplit['+i+'] = '+strSplit[i]);
}
}
The console output (where the tab between 1st and 2nd item is not recognised):
strSplit[0] = 0.02194 0.028940568
strSplit[1] = 0.05227
strSplit[2] = 0.040229885
strSplit[3] = 0.04650
strSplit[4] = 0.035630689
strSplit[5] = 0.07055
strSplit[6] = 0.015557256
strSplit[7] = 0.01960
strSplit[8] = 0.03527
strSplit[9] = 0.05276
strSplit[10] = 0.05669
strSplit[11] = 0.05680
strSplit[12] = 0.04464
strSplit[13] = 1
Unsure if the string copies correctly with all tabs, but here it is:
const str = `0.02194 0.028940568 0.05227 0.040229885 0.04650 0.035630689 0.07055 0.015557256 0.01960 0.03527 0.05276 0.05669 0.05680 0.04464 1`;
function testTab(str) {
var strSplit = str.split('\t');
for (i = 0; i < strSplit.length; i++) {
console.log('strSplit[' + i + '] = ' + strSplit[i]);
}
}
testTab(str)
Thanks for your suggestions, it inspired me to review all options.
I changed the delimiters in the regex so that the split now reads:
var strSplit = str.split(/\t/);
For some reason it now works.

How to get the index of a string in google docs using google App Script

I want to search for a string and then replace it with an image on google docs. For that, I want to get the index of the string and then replace it with an image. But I'm unable to get the index of the string so far.
Below is a snippet of what I am doing:
var element = '<<19>>';
options = {muteHttpExceptions: true};
var resp = UrlFetchApp.fetch(mylist[x-1], options);
var image = resp.getBlob();
//getting the index of element and then replacing it with image
var rangeElement = body.findText(element);
var foundElement = rangeElement.getStartOffset();
body.replaceText(element, body.insertImage(foundElement, image));
I've tried using findText(searchPattern) but it didn't work as it returns a range element and I'm getting output as 0 everytime.
This is how you find text on your document and replace it with an image:
function findAndReplaceWithImage() {
var element = "<<19>>";
var doc = DocumentApp.getActiveDocument().getBody();
var image = "your image url";
var blob = UrlFetchApp.fetch(image).getBlob();
var paragraphs = doc.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();
if (text === element) {
//Found your match
doc.removeChild(paragraphs[i]);
doc.insertImage(i, blob);
}
}
}
Hope this helps!

How to dynamically add <a> tags given an index of HTML page's string?

I'm making a search function for my website. So far, I've found the string the user searches for in the whole website, and I'm able to print the string and the context of the string. I have achieved this by using $.get on my HTML pages, then stripping the HTML to leave the pure text I want to search in. I then find the index of the string I'm looking for, then use substr to find the context of the input string (a few indexes ahead and behind).
Now, I need to link to the original page when a user clicks on a search result. My research says to use <a> tags, but how do I dynamically insert those into the HTML page with the index I have? And the index I have isn't even the complete page; it's stripped of tags.
These are the relevant parts of my code:
JavaScript:
function getIndicesOf(searchStr, str) { //get the indices of searchStr inside of str
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
function search() {
obj=document.getElementById("searchButton");
obj.onclick = function() {
var searchInput = document.getElementById('searchBox').value;
var allPageContent = ['chap/telem.php', 'chap/nestor.php', 'chap/aeolus.php', 'chap/calypso.php', 'chap/circe.php', 'chap/cyclops.php', 'chap/eumaeus.php', 'chap/hades.php','chap/ithaca.php', 'chap/lestry.php', 'chap/lotus.php', 'chap/nausicaa.php', 'chap/oxen.php', 'chap/penelope.php', 'chap/proteus.php', 'chap/scylla.php', 'chap/sirens.php', 'chap/wrocks.php']; //contains all text
var allText = '';
for (var i = 0; i < allPageContent.length; i++){
$.get(allPageContent[i], function(data){
var div = document.createElement("div");
div.innerHTML = data;
//allText = div.textContent || div.innerText || ""; //gets the text to search in, stripped of html
alltext = data;
allText = allText.replace(/(\r\n\t|\n|\r\t)/gm," ");
console.log(data);
var indices = getIndicesOf(searchInput, allText); //the variable indices is the array that contains the indices of the searched text in the main text
indices.forEach(findContext);
})
}
localStorage.output = '';
function findContext(currentValue, index) {
if (currentValue <= 16) {
searchContext = "..." + allText.substr(currentValue, 100) + "...";
} else {
searchContext = "..." + allText.substr(currentValue-15, 100) + "...";
}
localStorage.output = localStorage.output + searchContext + "<br /><br />";
}
console.log(localStorage.output);
};
};
HTML:
<script>document.getElementById("output").innerHTML = localStorage.output;</script>
It's a bit confusing what you're trying to achieve, considering your HTML, but replying to this
My research says to use <a> tags, but how do I dynamically insert
those into the HTML page with the index I have?
this would do the trick
var output = document.getElementById("output");
var a = document.createElement("a");
var linkText = document.createTextNode("my linked text");
a.appendChild(linkText);
a.href = "http://example.com";
output.appendChild(a);

Highlighting Exact Text Match

I have the following java userscript:
function highlightWord(word) {
var xpath = "//text()[contains(., '" + word + "')]";
var texts = document.evaluate(xpath, document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (n = 0; n < texts.snapshotLength; n++) {
var textNode = texts.snapshotItem(n);
var p = textNode.parentNode;
var a = [];
var frag = document.createDocumentFragment();
textNode.nodeValue.split(word).forEach(function(text, i) {
var node;
if (i) {
node = document.createElement('span');
node.style.backgroundColor = 'lightgreen';
node.appendChild(document.createTextNode(word));
frag.appendChild(node);
}
if (text.length) {
frag.appendChild(document.createTextNode(text));
}
return a;
});
p.replaceChild(frag, textNode);
}
}
highlightWord('office');
Would anyone be able to help me with finding a solution to only match the exact text of the highlightWord's that I add? For example, I want it to only match "office" and not "officer".
Thanks!
This answer
https://stackoverflow.com/a/2994336/2707021
should help. Essentially you need to apply word boundaries to the pattern match string on this line
var xpath = "//text()[contains(., '" + word + "')]";
You need to change the following line of your code
textNode.nodeValue.split(word).forEach(function(text, i) {
into the one shown below. This will highlight, only the word that you mention.
textNode.nodeValue.split(RegExp("\\b" + word + "\\b")).forEach(function (text, i) {
The XPath just extracts the entire text, the actual string search in your code happens in the above statement.

Categories

Resources