I have been struggling with a script I have been working on for a while. The problem is that when I run the script with text like:
Hi. apples are amazing.
I want to make only the a in apples capitalized, but instead the text comes out as:
Hi. Apples Are Amazing.
Here is the code:
function caps()
{
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText()
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lower = "abcdefghijklmnopqrstuvwxyx";
//while (() != null) {
//var search = text.findText('. a')
//var start = replace - 1
//text.deleteText(start, replace)
//text.insertText(start, " A")//}
for(var i=0; i<caps.length; i++)
{
var nextCaps = caps.charAt(i);
var nextLower = lower.charAt(i);
while (text.findText('. ' + nextLower) != null)
{
Logger.log(nextLower)
Logger.log(nextCaps)
var search = text.findText('. ' + nextLower)
var replace = search.getEndOffsetInclusive()
var start = replace - 1
text.deleteText(start, replace)
text.insertText(start, " " + nextCaps)
}
//var nextChar = caps.charAt(i);
//Logger.log(nextLower)
}
}
Basically, the code looks for ". a" and replaces it with ". A" (same with b, c, d and so on). If anyone can help me with this it would be very much appreciated.
The below code follows your example where you want to capitalize the first letter after the end of the first sentence. So long as that is the case this regex and replace will do that for any letters.
var str = 'Hi. apples are amazing.';
var reg = /\.\s./;
function replacement(match) {
return match.toUpperCase();
}
str = str.replace(reg, replacement);
Logger.log(str);
Related
I want to highlight in a text all the occurrences from a word that I have in my URL.
For the first occurrence everything works fine. But I don't know how to go to the next one.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(searchText, "<mark>" + searchText + "</mark>");
el.innerHTML = marked;
}
}
I have tried to add a while(window.find(searchText) before the if but it doesn't work, it seems to loop only on the first occurence of my word.
Thanks in advance
If you're not using regex then it'll only replace the first occurrence, you might try this, Also modify the regex as per your needs.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(
RegExp(`(${searchText})`),
"<mark>" + searchText + " </mark>");
el.innerHTML = marked;
}
}
Note: The match is case sensitive
I am making an html page which is a typer of a foreign script.
my progress: HERE
Here's the entire javascript:
function getReplacedText(latinText) {
if (!latinText) {
return "";
}
var replacedText = "";
for (var i = 0, len = latinText.length; i < len; i++) {
var curLetter = latinText[i];
var pos1Txt = latinText[i + 1];
var pos2Txt = latinText[i + 2];
if (!(curLetter == "")) {
var dualLetter = latreplaced[curLetter + pos1Txt];
if (dualLetter) {
replacedText += dualLetter;
i++;
continue;
}
}
replacedText += latreplaced[curLetter] || curLetter;
}
return replacedText;
}
var latreplaced = {
"u":"う",
"ku":"く",
"tsu":"つ",
};
function onLatinTextChange(txt) {
var replacedTextareaElem = document.getElementById("replaced_textarea");
var div = document.createElement("div");
var replacedHtmlEntities = getReplacedText(txt);
div.innerHTML = replacedHtmlEntities;
replacedTextareaElem.value = div.innerText;
}
The purpose of this project is to create a virtual phonetic keyboard to type certain forign scripts by only using Latin alphabets, without its keyboard setting installed.
Basically, if you enter an alphabet into the input <textarea>, it renders its corresponding foreign alphabet. (For instance, input 'u' > output 'う', input 'ku' > output 'く')
Here is my problem: So far I have enabled rendering an output when one or two alphabet is typed into the input box. But I cannot figure out how to enable the same by entering three alphabets. (For instance, input 'tsu' > output 'つ')
"u":"う", // <- can convert
"ku":"く", // <- can convert
"tsu":"つ", // <- cannot convert!
In the javascript code, there is a var called dualLetter, which goes by the following script:
var dualLetter = latreplaced[curLetter + pos1Txt];
How can I edit this part of code (or the entire javascript) to be able to convert 3 or more input alphabets? Do I need to make var tripleLetter, or create a whole new system? Any alternative ways would also be helpful.
[edit] a solution inspired by your code :
I changed the main function but this definitively works
live demo : https://jsfiddle.net/alias_gui3/wds426mq/12/
source code :
var dictionnary = {
"u":"う",
"ku":"く",
"tsu":"つ",
"test for spaces": "😍"
};
var maxLength = Object.keys(dictionnary)
.reduce((a, b) => a.length > b.length ? a : b) // get the longest word
.length; // and it's length
function translate (text) {
var translated = "";
var cur = 0;
while (cur < text.length) {
var testedPhoneme;
var symbol = undefined;
for (var length = maxLength; length > 0; length --) {
testedPhoneme = text.substr(cur, length);
if (dictionnary[testedPhoneme]) {
symbol = dictionnary[testedPhoneme];
break; // stop the loop
}
}
if (symbol) {
translated += symbol;
cur += testedPhoneme.length;
}
else {
translated += text[cur]
cur++;
}
}
return translated
}
function onLatinTextChange(txt) {
var replacedTextareaElem = document.getElementById("replaced_textarea");
var div = document.createElement("div");
var replacedHtmlEntities = translate(txt);
div.innerHTML = replacedHtmlEntities;
replacedTextareaElem.value = div.innerText;
}
[previous post] a simple solution :
I suggest you split your text using spaces
If i understand well, you want to type u ku tsu to get うくつ, not ukutsu, if this is right then something like that could work :
const dictionnary = {
"u": "う",
"ku": "く",
"tsu": "つ"
var phonemes = text.split(' ') // split text by spaces
var translatedArray = phonemes.map(function (phoneme) {
return dictionnary[phoneme] || phoneme
// will return the latin phoneme if it is not in the dictionnary
})
translatedString = translatedArray.join('')
Explanation. I am new to VueJS and JavaScript and I am trying to setup a search bar. So far, it works well, but I have one issue with it. I would like to be able to search through a description of an object even if the words I typed in the search bar are not in the correct order.
Example.
The string in the description would be "Gucci blue belt". If I type "Gucci blue", the result shows up since the description contains those words in this exact order. Therefore, I would like to add the functionality for which I can type "Gucci belt" and the item with the description "Gucci blue belt" would show up.
My current code in the computed section in VueJS
filteredsortedobjects (){
return this.sortedobjects.filter(object => {
var Objectslist_n = object.name;
var Objectslist_q = object.quantity;
var Objectslist_c = object.category;
var Objectslist_s = object.section;
var Objectslist_d = object.description;
var Objectslist_date = object.reception_date;
var Input = this.searchQuery;
/* Form arrays with all the information in the table */
var Objectslist_nq = Objectslist_n.concat(Objectslist_q);
var Objectslist_nqc = Objectslist_nq.concat(Objectslist_c);
var Objectslist_nqcs = Objectslist_nqc.concat(Objectslist_s);
var Objectslist_nqcsd = Objectslist_nqcs.concat(Objectslist_d);
var Objectslist_nqcsddate = Objectslist_nqcsd.concat(Objectslist_date);
/* Filtered variables */
var F_Objectslist = RemoveAccents(Objectslist_nqcsddate.toLowerCase());
var F_Input = RemoveAccents(this.searchQuery.toLowerCase());
/* Function to remove accents */
function RemoveAccents(str) {
var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
str = str.split('');
var strLen = str.length;
var i, x;
for (i = 0; i < strLen; i++) {
if ((x = accents.indexOf(str[i])) != -1) {
str[i] = accentsOut[x];
}
}
return str.join('');
};
console.log(F_Objectslist);
console.log(F_Input);
return F_Objectslist.includes(F_Input)
})
}
I am aware that the function to remove accents is not yet used since I have been testing things.
What I have tried doing. I have tried setting the variable F_Input (what is being written in the search bar) and F_Objectslist (a variable containing an array with all the words for the items, for instance, the names, the category, the section, the quantity, a description and a date) as strings by array.split(" "). That way, I was able to have an array of strings in this format in the console ["word", "word2", ...] for both my variables.
From this point, I am unsure on how to check if the strings in my F_Input array are all present in the array for F_Objectslist even if they are in a different order.
Thank you so much for your time!
Split F_Input on " ", then you can use 'Array.prototype.map()' to loop through the F_Input array of search terms using the same technique you have now.
Notice that I've chained all these together with a final call to the .every() method. That last one says that every map operation (search) must result in a true (or the result of the map operation must result in an array full of nothing but true);
const F_Objectslist = "this is search term, and this is term search".split(' ');
const F_Input = "search term";
let result = search(F_Objectslist, F_Input);
console.log(result);
let notFoundResult = search(F_Objectslist, "search dog");
console.log(notFoundResult);
function search(text, terms) {
return terms.split(' ').map(term =>text.includes(term)).every(found=>found===true);
}
I think you were already pretty close, I would approach it like this
function searchString(input, match) {
let is_a_match = true;
const match_arr = match.split(' ');
const input_arr = input.split(' ');
input_arr.forEach(word => {
if (match_arr.indexOf(word) === -1) {
is_a_match = false;
}
});
return is_a_match;
}
A working fiddle can be found here
Here is my answer.
I managed to make a quite responsive search bar that seeks information in the array! Here is the code if anyone is curious about it!
page.vue inside computed
filteredsortedobjects (){
return this.sortedobjects.filter(object => {
var Objectslist_n = "a" + object.name;
var Objectslist_c = object.category;
var Objectslist_s = object.section;
var Objectslist_q = object.quantity;
var Objectslist_d = object.description;
var Objectslist_date = object.reception_date;
var Input = this.searchQuery;
/* Form arrays with all the information in the table */
var Objectslist_nc = Objectslist_n + " " + Objectslist_c;
var Objectslist_ncs = Objectslist_nc + " " + Objectslist_s;
var Objectslist_ncsq = Objectslist_ncs + " " + Objectslist_q;
var Objectslist_ncsqd = Objectslist_ncsq + " " + Objectslist_d;
var Objectslist_ncsqddate = Objectslist_ncsqd + " " + Objectslist_date;
/* Filtered variables */
var F_Objectslist = RemoveAccents(Objectslist_ncsqddate.toLowerCase()).split(" ") + " ";
var F_Input = RemoveAccents(this.searchQuery.toLowerCase()).split(" ");
/* Function to remove accents */
function RemoveAccents(str) {
var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
str = str.split('');
var strLen = str.length;
var i, x;
for (i = 0; i < strLen; i++) {
if ((x = accents.indexOf(str[i])) != -1) {
str[i] = accentsOut[x];
}
}
return str.join('');
};
return F_Input.every(object => {
if (F_Objectslist.indexOf(object) === -1) {
}
else {
return F_Objectslist.indexOf(object)
}
})
})
}
I have an input with a v-model="searchQuery" attribute. Also, there is a table containing
<tr id="tr" v-for="object in filteredsortedobjects" v-bind:key="object.name">
<td>
<p>{{ object.name }}</p>
</td>
<td>
<p>{{ object.category }}</p>
</td>
<td>
<p>{{ object.section }}</p>
</td>
<td>
<p>{{ object.quantity }}</p>
</td>
<td>
<p>{{ object.description }}</p>
</td>
<td>
<p>{{ object.reception_date }}</p>
</td>
</tr>
The object.something are imported from a JSON file using
<script>
import objects from "./Database/Objects.json";
</script>
You would probably have to set some data information in the data() section
searchQuery: ""
I want to count number of occurence of BB code like word (example: [b] [/b]).
I tried
(str.match(/\[b\]/g) str.match(/\[\/b\]/g))
None of this worked, please help !!!
Edit
document.getElementById('textarea').value = 'HIiiiiiiiiiii [b]BOld[/b]';
var str = document.getElementById('textarea').value;
Answer:
if (str.match(/\[b\]/g).length == str.match(/\[\/b\]/g)).length) {alert("Fine");}
This regex will match a BB code opening tag:
str.match(/\[[a-z]*\]/g)
Edit: Here's some code that will do exactly what you want including creating an array of errors listing all missing closing tags. This code uses the underscore library for the groupBy() call.
jsFiddle
var bbcode = 'HI[i]iii[i]iii[/i]iii [b]BOld[/b] yahhh [img]url[/img]';
var matches = bbcode.match(/\[[a-z]*\]/g); //get the matches
var tags = _.groupBy(matches, function(val) {
val = val.substring(1, val.length-1);
return val;
});
var errors = [];
for (var tag in tags) {
var regex = '\\\[/' + tag + '\\\]';
if (bbcode.match(regex).length != tags[tag].length) {
errors.push('Missing a closing [/' + tag + '] tag');
}
}
console.log(errors);
Replace occurences until there aren't any; keep track of the amount on the way:
var regexp = /\[[a-z]\](.*?)\[\/[a-z]\]/i;
var str = "test [b]a[/b] test [i]b[/i] [b]d[/b] c";
var newstr = str;
var i = 0;
while(regexp.test(newstr)) {
newstr = newstr.replace(regexp, "");
i++;
}
alert(i); // alerts 3
i want to strip just text values from below html with js.
var Str = "<span style="">MY name is KERBEROS.</span><B>HELLO Everbody</B>"
All text strips with codes that is below;
[^<>]+(?=[<])
But i want to strip just UPPERCASE words. Clresult must be: MY, KERBEROS, HELLO
Thank you already now for your suggestions.
Regards,
Kerberos
Here is your code, gives output: MY,KERBEROS,HELLO
<script>
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "");
};
String.prototype.getUpperCaseWords = function()
{
var matchTag1 = /\b([A-Z])+\b/g;
var o = this.match(matchTag1);
return o;
};
var Str = "<span style=''>MY name is KERBEROS.</span><B>HELLO Everbody</B>";
var out1 = Str.stripHTML();
var out2 = out1.getUpperCaseWords();
alert(out2);
</script>
This is another solution in JavaScript using just one line of regex:
String.prototype.stripHTML = function()
{
var matchTag = /<(?:.|\s)*?>/g;
return this.replace(matchTag, "").match(/\b([A-Z])+\b/g);
};
var Str = "<span style=''>MY name is SATYA PRAKASH.</span><B>HELLO Everyone</B>";
var out1 = Str.stripHTML();