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
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('')
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>
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);
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();