I want to get the first space delimited string out of a longer string with multiple words in it. Lots of examples, all of which do something like .split(" "). Google Apps script tells me that split can't take null as a parameter. I tried setting a variable to " ", even tried String.fromCharCode(32), but GAS tells me that's null.
Search, indexOf have the same issue -- GAS tells me it can't do those with a null argument. How do I tell GAS that a single space is not a null?
Yes, this was a case of the string being null in some cases. I was using the file method getDescription. After using Logger a bunch, I found the problem and I solved those some cases by this check.
var desctext = file.getDescription();
if ( desctext == null) { desctext = " ; ; ; "};
It's been many years since I've done anything with REGEX, and is was confusing then. Any suggestions on a good site for learning it?
I also changed my delimiter to a semicolon, even though it makes the user input more tedious.
The background is that I'm writing a script to work with a photo inventory where I want to keep the important information in the photo's EXIF. Not sure if Google is actually storing it there, but in any case the only fields available aside from the date and filename is the description. So I'm having the users type in coded filenames and descriptions with semicolon delimiters to indicate things like category, item name, status and value.
Related
Welcome,. I am making an application to recognize the voice and convert it to text and then compare and correct it, so far everything from converting voice to text and comparing it works perfectly, but there are some words that I want to change or change their wording ... I tried to put it under an if statement As in the place of the code, and it was working well in terms of application, but it affects performance significantly So I was asking if I could make something like a filter so that it contains a large group of words and at the same time maintains a good performance for the application.
An example of what i did :
If(inputText.getText.toString.contains("A Specific Word ")){
String before ;
String after ;
before = inputText.getText.toString;
after = before.replaceAll("A Specific Word", "ASW" );
inputText.setText(after);
}
But this Causes performance problems.
I think you can simply enhance it by usingthis code:
try{
String sentence = inputText.getText().toString();
inputText.setText(sentence.replaceall("Hello", "Hi")); // Replace with Your words
}catch(Exception e){
System.out.println("Couldn't find Hello");
}
Using try-catch statements it will not check if the word is in there but if it is not there, then also it will continue and will safely pass over the statement.
What is different?
That we are not finding the required word in the sentence which will save time will longer sentences.
I have a graphql query that I'm sending to the server (uses apollo-server) using fetch. I strip all extra whitespace from the query string before I send it. Should I be worried?
const query = `
{
thing {
id
name
relatedThing {
id
name
createdAt
}
}
}`
after query.replace(/\s+/g, ' ') I've got...
"{ thing { id name relatedThing { id name createdAt } } }"
I haven't had any complains from the server or any weird behaviour, but I don't understand the server demands and whether there's a possibility this could break some queries. Is it possible that I can break some queries by doing this?
From the spec:
White space is used to improve legibility of source text and act as separation between tokens, and any amount of white space may appear before or after any token. White space between tokens is not significant to the semantic meaning of a GraphQL Document, however white space characters may appear within a String or Comment token... Like white space, line terminators are used to improve the legibility of source text, any amount may appear before or after any other token and have no significance to the semantic meaning of a GraphQL Document. Line terminators are not found within any other token.
In other words, there's nothing wrong with what you are doing. There's just two things to keep in mind:
If your queries include String literals, that particular regex express will also change the value of the String literal as well if it includes more than one space.
GraphQL returns errors with a location that includes both the line number and character number where the error occurred. By transforming your queries like this, that information will reflect the transformed query and not your original one.
I am using javascript in a Mirth transformer. I apologize for my ignorance but I have no javascript training and have a hard time successfully utilizing info from similar threads here or elsewhere. I am trying to trim a string from 'Room-Bed' to be just 'Bed'. The "Room" and "Bed" values will fluctuate. All associated data is coming in from an ADT interface where our client is sending both the room and bed values, separated by a hyphen, in the bed field creating unnecessary redundancy. Please help me with the code needed to produce the result of 'Bed' from the received 'Room-Bed'.
There are many ways to reduce the string you have to the string you want. Which you choose will depend on your inputs and the output you want. For your simple example, all will work. But if you have strings come in with multiple hyphens, they'll render different results. They'll also have different performance characteristics. Balance the performance of it with how often it will be called, and whichever you find to be most readable.
// Turns the string in to an array, then pops the last instance out: 'Bed'!
'Room-Bed'.split('-').pop() === 'Bed'
// Looks for the given pattern,
// replacing the match with everything after the hyphen.
'Room-Bed'.replace(/.+-(.+)/, '$1') === 'Bed'
// Finds the first index of -,
// and creates a substring based on it.
'Room-Bed'.substr('Room-Bed'.indexOf('-') + 1) === 'Bed'
As the title states, I can't get any way to filter all CommentThreads using the "?" searchTerm, this returns an empty list of CommentThreads.
Tried \? , \?, plain %03F, unicode \u0003F. Nothing seems to work.
Is there a way to filter by the questionmark ? I'm trying to retrieve all the questions from a video and if I can't filter this way it means I have to pull down everything and filter locally, which is really expensive (quota-wise).
Here is the api explorer url :
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.commentThreads.list?part=id%252Csnippet&maxResults=10&order=time&searchTerms=%253F&textFormat=html&videoId=o4lMYiwKYRs&fields=items(replies%252Csnippet)%252CnextPageToken&_h=18&
I don't know if this is a bug or not, but it seems that the searchTerms parameter has its own rules to make itself works or filter the results.
Let us use this videoId=2ecT9zf1QZU that has a comments of:
24
kobe bryant?
24kobe
?kobe
kobe? bryant
IDOL24
If we use searchTerms=?, we will get 0 result like the one you experienced, because I think it does not work with special character alone or words that have this special character. (eg. ?)
If we use searchTerms=kobe, we will get 3 results, (kobe bryant?, ?kobe and kobe? bryant) so it work with a word without special character.
Now, we use searchTerms=?kobe and searchTerms=kobe?, we will get 0 result because of the special character ?.
What if we use searchTerms=yant (from the word bryant), the result is 0, because there is no word in the result that have a word yant.
So meaning there are some rules or limitation in using this searhTerms.
I hope this information helps you.
ok i do have this following data in my div
<div id="mydiv">
<!--
what is your present
<code>alert("this is my present");</code>
where?
<code>alert("here at my left hand");</code>
oh thank you! i love you!! hehe
<code>alert("welcome my honey ^^");</code>
-->
</div>
well what i need to do there is to get the all the scripts inside the <code> blocks and the html codes text nodes without removing the html comments inside. well its a homework given by my professor and i can't modify that div block..
I need to use regular expressions for this and this is what i did
var block = $.trim($("div#mydiv").html()).replace("<!--","").replace("-->","");
var htmlRegex = new RegExp(""); //I don't know what to do here
var codeRegex = new RegExp("^<code(*n)</code>$","igm");
var code = codeRegex.exec(block);
var html = "";
it really doesn't work... please don't give the exact answer.. please teach me.. thank you
I need to have the following blocks for the variable code
alert("this is my present");
alert("here at my left hand");
alert("welcome my honey ^^");
and this is the blocks i need for variable html
what is your present
where?
oh thank you! i love you!! hehe
my question is what is the regex pattern to get the results above?
Parsing HTML with a regular expression is not something you should do.
I'm sure your professor thinks he/she was really clever and that there's no way to access the DOM API and can wave a banner around and justify some minor corner-case for using regex to parse the DOM and that sometimes it's okay.
Well, no, it isn't. If you have complex code in there, what happens? Your regex breaks, and perhaps becomes a security exploit if this is ever in production.
So, here:
http://jsfiddle.net/zfp6D/
Walk the dom, get the nodeType 8 (comment) text value out of the node.
Invoke the HTML parser (that thing that browsers use to parse HTML, rather than regex, why you wouldn't use the HTML parser to parse HTML is totally beyond me, it's like saying "Yeah, I could nail in this nail with a hammer, but I think I'm going to just stomp on the nail with my foot until it goes in").
Find all the CODE elements in the newly parsed HTML.
Log them to console, or whatever you want to do with them.
First of all, you should be aware that because HTML is not a regular language, you cannot do generic parsing using regular expressions that will work for all valid inputs (generic nesting in particular cannot be expressed with regular expressions). Many parsers do use regular expressions to match individual tokens, but other algorithms need to be built around them
However, for a fixed input such as this, it's just a case of working through the structure you have (though it's still often easier to use different parsing methods than just regular expressions).
First lets get all the code:
var code = '', match = [];
var regex = new RegExp("<code>(.*?)</code>", "g");
while (match = regex.exec(content)) {
code += match[1] + "\n";
}
I assume content contains the content of the div that you've already extracted. Here the "g" flag says this is for "global" matching, so we can reuse the regex to find every match. The brackets indicate a capturing group, . means any character, * means repeated 0 or more times, and ? means "non-greedy" (see what happens without it to see what it does).
Now we can do a similar thing to get all the other bits, but this time the regex is slightly more complicated:
new RegExp("(<!--|</code>)(.*?)(-->|<code>)", "g")
Here | means "or". So this matches all the bits that start with either "start comment" or "end code" and end with "end comment" or "start code". Note also that we now have 3 sets of brackets, so the part we want to extract is match[2] (the second set).
You're doing a lot of unnecessary stuff. .html() gives you the inner contents as a string. You should be able to use regEx to grab exactly what you need from there. Also, try to stick with regEx literals (e.g. /^regexstring$/). You have to escape escape characters using new RegExp which gets really messy. You generally only want to use new RegExp when you need to put a string var into a regEx.
The match function of strings accepts regEx and returns a collection of every match when you add the global flag (e.g. /^regexstring$/g <-- note the 'g'). I would do something like this:
var block = $('#mydiv').html(), //you can set multiple vars in one statement w/commas
matches = block.match(/<code>[^<]*<\/code>/g);
//[^<]* <-- 0 or more characters that aren't '<' - google 'negative character class'
matches.join('_') //lazy way of avoiding a loop - join into a string with a safe character
.replace(/<\/*code>/g,'') //\/* 0 or more forward slashes
.split('_');//return the matches string back to array
//Now do what you want with matches. Eval (ew) or append in a script tag (ew).
//You have no control over the 'ew'. I just prefer data to scripts in strings