JS RegExp capture all groups and pos for each match - javascript

Statement:
I am new to RegExp and trying to learn capture groups in javascripts
I am using https://regex101.com/r/COYhIc/1 for testing
see attached image for character pos column of each match by https://regex101.com
Objective:
I want to print all matches and groups at console (Done)
I want to print character position of each match [see image](remaining)
JSFIDDLE: https://jsfiddle.net/bababalcksheep/p28fmdk4/68/
JavaScript:
function parseQuery(query) {
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
if (isRE) {
try {
query = new RegExp(isRE[1], isRE[2]);
} catch (e) {}
}
return query;
}
var str = $('#str').val();
var regex = parseQuery($('#reg').val());
//
var result;
var match_no = 0;
var output = '';
while ((result = regex.exec(str)) !== null) {
match_no++;
output += `\nMatch ${match_no}\n`;
output += `Full Match, ${ result[0]} , Pos\n`;
for (i = 1; i < result.length; i++) {
output += `Group ${i}, ${ result[i]} , Pos\n`;
}
}
console.log(output);

In your output field use index and lastIndex. exec returns an object with a index property.
output += `Full Match, ${ result[0]} , Pos ${result.index} - ${regex.lastIndex}\n `;
Update for the groups:
I have used a small logic to get the indices:
var m = new RegExp(result[i]);
output += `Group ${i}, ${ result[i]}, Pos ${$('#str').val().match(m).index} - ${regex.lastIndex} \n`;
function parseQuery(query) {
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
if (isRE) {
try {
query = new RegExp(isRE[1], isRE[2]);
} catch (e) {}
}
return query;
}
var str = $('#str').val();
var regex = parseQuery($('#reg').val());
//
var result;
var match_no = 0;
var output = '';
while ((result = regex.exec(str)) !== null) {
match_no++;
output += `\nMatch ${match_no}\n`;
output += `Full Match, ${ result[0]} , Pos ${result.index} - ${regex.lastIndex}\n `;
for (i = 1; i < result.length; i++) {
var m = new RegExp(result[i]);
output += `Group ${i}, ${ result[i]}, Pos ${$('#str').val().match(m).index} - ${regex.lastIndex} \n`;
}
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="form-group">
<label for="str">String:</label>
<input type="text" class="form-control" id="str" value="source=100, delta=2, source=2121, delta=5">
</div>
<div class="form-group">
<label for="regex">Regex:</label>
<input type="text" class="form-control" id="reg" value="/(source=(\d+))/g">
</div>
<div id="result">
</div>
</div>
FIDDLE

According to docs RegExp.exec, you can retrieve it using index property. So I would add this line into your snippet to retrieve column position for your full match:
`${result.index}-${result.index + result[0].length}`
For subgroups, JS doesn't retrieve index, so a workaround can be achieved using indexOf:
const initialSubGroupIndex = str.indexOf(result[i], result.index);
`${initialSubGroupIndex}-${initialSubGroupIndex + result[i].length}`

Related

How to find/remove last text portion of innerHTML

I have a <div> element that contains both html elements and text. I want to find/remove the last or the last nth or the nth text only portion of it.
So for example
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
If I had a method to delete the last text character, the first call would delete z and the second call would delete g. Or if I had a method to find the 4th character, it would return d.
It sounds like you only care about the text nodes, so probably something like this so you can just delete the nth character:
var div = document.getElementById("foo");
const getTextNodes = (el, nodes) => {
nodes = nodes || [];
for (var i = 0; i < el.childNodes.length; i++) {
var curNode = el.childNodes[i];
if (curNode.nodeName === "#text") {
if (curNode.textContent.trim().length) {
nodes.push(curNode);
}
} else {
getTextNodes(curNode, nodes);
}
}
return nodes;
}
console.log(getTextNodes(div).map((el) => el.textContent));
const deleteNthCharacter = (el, n) => {
n--; // since we want to be "1 indexed"
const nodes = getTextNodes(el);
let len = 0;
for (let i = 0; i < nodes.length; i++) {
const curNode = nodes[i];
if (len + curNode.textContent.length > n) {
curNode.textContent = curNode.textContent.substring(0, n - len) + curNode.textContent.substring(n + 1 - len);
break;
} else {
len += curNode.textContent.length;
}
}
}
deleteNthCharacter(div, 2);
deleteNthCharacter(div, 7);
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
If I understood your question correctly this should do the trick:
function deleteLastChar(targetId){
const target = document.getElementById(targetId);
let lastWithText = -1;
//find last child that has text set
target.childNodes.forEach((child, iter) => {
if(child.innerText != undefined && child.innerText.length > 0){
lastWithText = iter;
}
});
// exit if no valid text node was found
if(lastWithText === -1)
return;
const lastNode = target.childNodes[lastWithText];
lastNode.innerText = lastNode.innerText.slice(0, -1);
}
deleteLastChar("foo")
deleteLastChar("foo")
deleteLastChar("foo")
deleteLastChar("foo")
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
If I understand the question this is probably what you're looking for
let x = document.getElementById('foo').children;
function erase() {
for (let i = x.length - 1; i >=0; i--) {
if(x[i].textContent.length > 0) {
const textC = x[i].textContent;
x[i].textContent = textC.substring(0, textC.length - 1);
return;
}
}
}
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
<button onclick="erase()">Erase</button>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="foo">
<span id="bar">abcdefg</span><br>
<span id="baz">z</span><br><br>
<div id="result"></div>
<div id="result2"></div>
</div>
<script type="text/javascript">
var s = function(x){
return document.querySelector(x)
}
log = console.log;
var span1 = s("#bar")
var span2 = s("#baz")
var result = s("#result")
var result2 = s("#result2")
var res = span1.innerText.charAt(4)
// with the charAt method
result.innerText = " Result is : " +res+"\n\n"
// with regular Expression
var reg = /e/
result2.innerText = " Result2 is : " +span1.innerText.match(reg)
</script>
</body>
</html>

How can I create a secret message app using the square code method?

I need to create a secret message app, such that a text:
"If man was meant to stay on the ground, god would have given us roots."
is normalized to:
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots"
And the normalised text forms a rectangle (​r x c​) where ​c​ is the number of columns and ​r​ is the number of rows such that ​c >= r​ and ​c - r <= 1​,
So for instance the normalized text is 54 characters long, dictating a rectangle with ​c = 8​ and ​r = 7​:
"ifmanwas"
"meanttos"
"tayonthe"
"groundgo"
"dwouldha"
"vegivenu"
"sroots "
Then the coded message is obtained by reading down the columns going left to right
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
and further split to
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau"
The resulting cypher text for a non perfect rectangle can only have a single whitespace for the last rows.
"imtgdvs"
"fearwer"
"mayoogo"
"anouuio"
"ntnnlvt"
"wttddes"
"aohghn "
"sseoau "
This what I have done so far, I could only get my normalised text, but I am doing something wrong to convert it to a rectangle and to get a cypher text out of it.
const output = document.querySelector('#encoded_rectangle');
const encodedChunks = document.querySelector('#encoded_chunks');
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
const error = document.querySelector('#alert');
const encodeMessage = () => {
let message = string.value;
function wordCount() {
return message.split(" ").length;
}
if (wordCount < 2 || message.length < 50) {
error.innerHTML = "Invalid message, Input more than one word and at Least 50 characters!";
return false;
}
function normaliseMessage() {
return message.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
}
function rectangleSize() {
return Math.ceil(Math.sqrt(normaliseMessage.length));
}
function splitRegEx() {
return new RegExp(".{1," + rectangleSize + "}", "g");
}
function plaintextSegments() {
return normaliseMessage.match(splitRegEx);
}
function ciphertext() {
var columns = [],
currentLetter, currentSegment;
var i, j;
for (let i = 0; i < rectangleSize; i++) {
columns.push([]);
}
for (i = 0; i < plaintextSegments.length; i++) {
currentSegment = plaintextSegments[i];
for (j = 0; j < columns.length; j++) {
currentLetter = currentSegment[j];
columns[j].push(currentLetter);
}
}
for (i = 0; i < columns.length; i++) {
columns[i] = columns[i].join("");
}
return columns.join("");
}
function normalizeCipherText() {
return ciphertext.match(splitRegEx).join(" ");
}
text.innerHTML = plaintextSegments();
encodedChunks.innerHTML = ciphertext();
output.innerHTML = normalizeCipherText();
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
<p id="alert"></p>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
</form>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
<div class="box">
<h3>Encoded Chunks</h3>
<p id="encoded_chunks">
</p>
</div>
<div class="box">
<h3>Encoded Rectangle</h3>
<p id="encoded_rectangle">
</p>
</div>
Most of your code is constructed of very short methods.
Usually I'd consider a good practice, but in this case I think it just made the code less readable.
Additionally, I have to say that the HTML part wasn't necessary in terms of solving the issue - which was clearly Javascript/algorithm related.
This is my solution, which can be modified to match your context:
const input = "If man was meant to stay on the ground, god would have given us roots.";
const normalizedInput = input.replace(/[^\w]/g, "").toLowerCase();
const length = normalizedInput.length;
const cols = Math.ceil(Math.sqrt(length));
const rows = Math.ceil(length / cols);
var cypherText = "";
for (let i = 0; i < cols; i ++) {
for (let j = i; j < normalizedInput.length; j += cols) {
cypherText += normalizedInput[j];
}
cypherText += '\n';
}
console.log(cypherText);
This is what I came up with
const output = document.querySelector('#encoded_rectangle');
const encodedChunks = document.querySelector('#encoded_chunks');
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
const error = document.querySelector('#alert');
const encodeMessage = () => {
let message = string.value;
var normalisedText = message.replace(/[^a-zA-Z0-9]/g, "");
var textCount = normalisedText.length;
if (textCount < 50) {
console.log("Invalid message, Input more than one word and at Least 50 characters!");
return false;
}
var higest = Math.ceil(Math.sqrt(textCount));
var lowest = Math.ceil(textCount/higest);
var rect = [];
var coded = [];
var innerObj = {};
var resulting = "";
rect = rectangleSize(higest,lowest,normalisedText);
//read text from top-down i hotago!!!
coded = readFromTopDown(rect, higest);
coded.forEach(co => {
resulting += co.trim();
});
//nwa idi sharp, nice logic
console.log("Normalized: " + normalisedText);
console.log("Count: " + textCount);
console.log(rect);
console.log(coded);
console.log("Resulting: " + resulting);
function rectangleSize(higest, lowest, normalise) {
var rect = [];
var startIndex = 0;
for(var i = 0; i < lowest; i++){
if(i !== 0)
startIndex += higest;
if(normalise.substring(startIndex, startIndex + higest).length == higest){
rect.push(normalise.substring(startIndex, startIndex + higest))
}else{
//get the remainder as spaces
var spaces = higest - normalise.substring(startIndex, startIndex + higest).length;
var textI = normalise.substring(startIndex, startIndex + higest);
var str = textI + new Array(spaces + 1).join(' ');
rect.push(str);
}
}
return rect;
}
function readFromTopDown(rect, higest) {
var coded = [];
for(var i = 0; i < higest; i++){
var textMain = "";
rect.forEach(re => {
textMain += re.substring(i, i+1);
});
coded.push(textMain);
}
return coded;
}
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
<p id="alert"></p>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
</form>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
<div class="box">
<h3>Encoded Chunks</h3>
<p id="encoded_chunks"></p>
</div>
<div class="box">
<h3>Encoded Rectangle</h3>
<p id="encoded_rectangle"></p>
</div>
Try and see

How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?

enter image description here
How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?
You can check if the character of the string is uppercase by comparing the ASCII code. If it's between 65 & 90, the character is in uppercase.
Then by applying toUpperCase & toLowerCase methods will transform uppercase alphabets into lowercase and vice-versa.
function isUpperCase(c) {
return c >= 65 && c <= 90;
}
var string = "AaBbCcDd *+-";
var updatedString = string.split("").map(c => isUpperCase(c.charCodeAt(0)) ? c.toLowerCase() : c.toUpperCase()).join("");
console.log("Original String:: " + string);
console.log("Transformed String:: " + updatedString);
You can use this code alternate character
function alternate(changeString) {
var charArray = changeString.toLowerCase().split("");
for (var i = 1; i < charArray.length; i += 2) {
charArray[i] = charArray[i].toUpperCase();
}
return charArray.join("");
};
var text = "Test";
console.log(alternate(text));
For the transformation, you can use the following:
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
}
A complete example here: (although it isn't exact the same that is in your pic)
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
return result;
}
$('#text').on('input', function(){
$('#display').val(convert(this.value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>input</label><input id="text" />
<label>display</label><input id="display" disabled />
Please refer below code may be it will help you,
Keyup event will work each character
$(document).ready(function(){
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
$("#text").keyup(function(){
var l =this.value.length;
var s =this.value;
var r =new Array();
for(var i=0;i<l;i++){
if(upperCase.test(s[i])){
r.push(s[i].toString().toLowerCase());
}
if(lowerCase.test(s[i])){
r.push(s[i].toString().toUpperCase());
}
}
$("#res").val(r.toString().replace(/\,/g, '').trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<br>
Result:<input type="text" id="res">

Add space after dot

Good day. I've got some problem.
I've got input where I wrote some information.
Example:
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
And I've got my controller.
Example:
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
How I can add space after dot? Who knows?
Here is link to jsfiddle with my example.
We achieve it by adding space to each splitted string other than first one and an empty string
function someCtrl($scope) {
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
var addSpace='';
if(i>0 && strt[i].trim().length>0){
addSpace=' ';
}
strt[i] = addSpace+strt[i].trim().charAt(0).toUpperCase() + strt[i].trim().substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
</div>
You can do this simply by changing strt.join('.') to strt.join('. ').
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].trim();
if(strt[i].length > 0) {
strt[i] = ' '+strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
This is working fiddle
I suggest creating a directive so that you can plugin this behaviour whenever required., rather than writing your ng-change in every controller.
In directive simple line element.val(event.target.value.split(".").join(". ")); will work for you., with help of directive controller parameter.
See example fiddle

HTML error in Google Apps Script for EVE Online

I am currently working on a little recreational Google Apps Script (GAS) for EVE Online and I have hit a brick wall when I am getting my server side functions talking to my client side ones.
HTML:
<form id="frm1" name = "mat_add">
<input width="1000" type="text" name="mat" value="Enter Item Here"><br />
<input type="button" value="Submit" name="mat_sub" onclick= "google.script.run.withSuccessHandler(onSuccess).shortlist(this.parentNode,document.getElementById('spn1').innerHTML)">
</form>
<span id="spn1"><table><tr><td>Type Name</td><td>Type ID</td></tr></table></span>
<script>
function onSuccess(output) {
document.getElementById(output[0]).innerHTML = output[1];
};
</script>
GAS:
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle('UMX Web App');
};
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
};
function shortlist(form,table) {
var arr = transpose(htmlToArray(table));
var item = form.mat;
if ( isNaN(item) ) {
var url = 'https://www.fuzzwork.co.uk/api/typeid2.php?format=xml&typename=' + item.toString();
} else {
var url = 'https://api.eveonline.com/eve/TypeName.xml.aspx?ids=' + item.toString();
};
var xml = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(xml);
var name = document.getRootElement().getChild('result').getChild('rowset').getChild('row').getAttribute('typeName').getValue();
if ( arr[0].indexOf(name) == -1 && name != 'Unknown Type' && name != 'bad item' ) {
arr[0].push(name);
arr[1].push(document.getRootElement().getChild('result').getChild('rowset').getChild('row').getAttribute('typeID').getValue());
};
var str = arrayToHTML(transpose(arr));
return ['spn1',str]
};
function arrayToHTML(arr) {
var i = 0;
var j = 0;
var str = '<table>';
while ( i < arr.length ) {
str = str + '<tr>';
while ( j < arr[i].length ) {
str = str + '<td>' + arr[i][j] + '</td>';
j += 1
};
str = str + '</tr>';
j = 0;
i += 1
};
str = str + '</table>';
return str
};
function htmlToArray(str) {
var arr1 = str.replace(/<tr>/g,'</tr>').split('</tr>');
var arr2 = [];
var i = 1;
var j = 1;
var x = [];
while ( i < arr1.length ) {
arr2.push([]);
x = arr1[i].replace(/<td>/g,'</td>').split('</td>');
while ( j < x.length ) {
arr2[arr2.length - 1].push(x[j]);
j += 2
};
j = 1;
i += 2
};
return arr2
};
function transpose(input) {
var output = [];
var i = 0;
var j = 0;
while ( i < input[0].length ) {
output.push([]);
while ( j < input.length ) {
output[i].push(input[j][i]);
j += 1
};
j = 0;
i += 1
};
return output
};
function direct(input) {
return input
}
The problem seems to be on the submit button because everything else is working fine. I have been looking for a workaround but that submit button is the only point of entry I can get and it will not accept more than one variable.
The problem seems to be on the submit button because everything else is working fine. I have been looking for a workaround but that submit button is the only point of entry I can get and it will not accept more than one variable.
Let's focus on this, and ignore all the irrelevant code. Basic question: how to get multiple inputs from a form to a server-side GAS function?
This example will demonstrate communication of the form object to the server, by throwing an error that contains all the received parameters. An errorHandler on the client side will alert with the received error message.
Index.html
<form id="frm1" name = "mat_add">
<input width="1000" type="text" name="mat" placeholder="Enter Item Here" /><br />
<input width="1000" type="text" name="mat2" placeholder="Enter Quantity Here" /><br />
<input type="button" value="Submit" name="mat_sub" onclick="google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.shortlist(this.parentNode)" />
</form>
<script>
function onSuccess(output) {
document.getElementById(output[0]).innerHTML = output[1];
};
function onFailure(error) {
alert( error.message );
}
</script>
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle('UMX Web App');
};
function shortlist(input) {
reportErr(JSON.stringify(input,null,2))
}
function reportErr(msg) {
throw new Error( msg );
}
Run this webapp, and here's your result:
The two named input elements, mat and mat2 were communicated to the server function shortlist() via the this.parent parameter. Since the button invoking this.parent in its clickHandler is contained in the frm1 form, all input elements of that form were included, and may be referenced on the server side as named properties of the input parameter of shortlist(). (NOT as array elements.)
The upshot of this is that your shortlist() function can be modified thusly:
function shortlist(input) {
var item = input.mat;
if ( isNaN(item) ) {
var url = 'https://www.fuzzwork.co.uk/api/typeid2.php?format=xml&typename=' + item;
} else {
var url = 'https://api.eveonline.com/eve/TypeName.xml.aspx?ids=' + item.toString();
};
...

Categories

Resources