get string matching then store second string and store it - javascript

have to search for classname with string matching "Routed:" then get the string of the following classname in this case "W000000" in the image below. there are over 65 of these on the page at any given time i just need to get the first one and store that value.

You could use a for loop for the elements and get the next one.
var tds = document.getElementsByClassName('ms-cellstyle ms-vb2');
var found = false;
var firstValue = '';
for (var i = 0; i < tds.length && !found; i++) {
if (tds[i].innerHTML.indexOf('Routed') >= 0 && i < tds.length - 1) {
firstValue = tds[i + 1].innerHTML;
found = true;
}
}
console.log(firstValue);

Related

Any alternative way of using this .length & .split()?

I want to split lower, upper & also the value of textBox without using .split() and also I want
to find the length of the string without using .length. Can anybody solve my problem I am tried but
I cannot find the exact logic for this problem.
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
function toUpper(input) {
var upperCase = uppercase.split(""); //other way to split uppercase
var lowerCase = lowercase.split(""); //other way to split lowercase
var inputText = input.split(""); //other way to split input
var newText = "";
var found;
for (var i = 0; i < inputText.length; i++) { //not using .length to other way to find the size of inputText
found = false;
for (var ctr = 0; ctr < lowerCase.length; ctr++) { //not using .length other way to find the size of lowerCase
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
You can count the length of a string using the array function reduce.
Reduce loops over all elements in an array and executes a function you give it to reduce it to one value, you can read more here.
To get reduce working on strings, you need to use Array.from, like this:
Array.from(lowerCase).reduce((sum, carry) => sum + 1, 0) // 26
Reduce accepts a starting argument, which we set to zero here.
This way you do not need to use the split or length functions.
You don't need to check if the input is in a string either, you can use charCodeAt() and fromCharCode().
If you take your input and loop through it using Array.from() then forEach, you can get something which looks like this:
function print() {
const input = document.querySelector('#input').value;
document.querySelector('#target').value = stringToUpper(input);
}
function stringToUpper(input) {
let output = "";
Array.from(input).forEach(char => output += charToUpper(char));
return output;
}
function charToUpper(char) {
let code = char.charCodeAt(0);
code >= 97 && code <= 122 ? code -= 32 : code;
return String.fromCharCode(code);
}
<div>
<input id="input" placeholder="enter text here">
</div>
<button onclick="print()">To Upper</button>
<div>
<input id="target">
</div>
The key line is where we take the output and add the char (as upper) to it:
output += charToUpper(char)
If you don't know about arrow functions, you can read more here
This line:
code >= 97 && code <= 122 ? code -= 32 : code;
is just checking if the char is lower case (number between 97 and 122) and if so, subtracting 32 to get it to upper case.
The reason it is subtract not add is in utf-16, the chars are laid out like this:
ABCDEFGHIJKLMNOPQRTUWXYZabcdefghijklmnopqrtuwxyz
See here for more
I don't know what you mean by "split the value of textBox", but one way to determine the length of a string without using .length would be to use a for...of loop and have a counter increment each time it runs to keep track of the number of characters in the string.
let string = 'boo'
let lengthCounter = 0
for (let char of string) {
lengthCounter++
}
//lengthCounter = 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
You can define your own split and length functions:
function mySplit(a){
var counter = 0;
rslt = [];
var val = a[counter];
while(typeof val != "undefined"){
rslt.push(a[counter]);
counter ++;
val = a[counter];
}
return rslt;
}
function myLength(a){
var counter = 0;
var val = a[counter];
while(typeof val != "undefined"){
counter ++;
val = a[counter];
}
return counter;
}
Your function now should be like:
function toUpper(input) {
var upperCase = mySplit(uppercase);
var lowerCase = mySplit(lowercase);
var inputText = mySplit(input);
var newText = "";
var found;
for (var i = 0; i < myLength(inputText); i++) {
found = false;
for (var ctr = 0; ctr < myLength(lowerCase); ctr++) {
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
The simplest way would be to just use the build in function of javascript .toUpperCase() (see example 1). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
Else if you insist on using a for.loop you may do so aswell (see example two). You do not need the split() function since a string already is an arrayof characters. Also be aware that not all characters in the web have lowercase counterparts, so the logic itself is flawed.
//REM: This lines are not required.
/*
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
*/
//REM: Version 1 (using string.toUpperCase())
(function toUpper1(input){
var tReturn = (input || '').toUpperCase();
console.log('toUpper1', tReturn);
return tReturn
}('abcDEFghiJKL'));
//REM: Version 2 (using your way)
(function toUpper2(input){
var tReturn = '';
if(input && input.length){
for(let i=0, j=input.length; i<j; i++){
tReturn += (input[i] === input[i].toLowerCase()) ? input[i].toUpperCase() : input[i]
}
};
console.log('toUpper2', tReturn);
return tReturn
}('abcDEFghiJKL'));

undefined parameter in js

I am receiving a type error stating that the array testA[i] is undefined whenever I add an input into the html page. I have the array set and i'm trying to add the value of currency to the array using the push method to add to the second part of the array i.e([0][currency])
function Test() {
var testA = [];
for (i = 0; i < 4; i++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i].push(currency);
}
}
var index = new Test();
any help as to why the array is undefined would be appreciated.
Note: I have now tried both testA.push(currency) and testA[i] = this.currency, and I still get the same error as before.
Note: the final version should have it loop through 4 different questions asked and each time adding these into an array. At the end of the loop a new variant of the array should be made and the new set of data entered will be added to it. something like
for(i = 0; i < 4; i++) {
testA[i] = i;
for(j = 0; j < 4; j++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i][j] = this.currency;
}
}
but at this point in time I'm just trying to get it to work.
You don't use the push method on a index. You use it on the array itself.
Replace this
testA[i].push(currency);
With this
testA.push(currency);
You need to perform push operation on the array directly.
testA.push(currency);
By executing testA[index] you will receive hold value. In JS it will always return undefined, if index is greater than array length.
Because your array is empty as the beginning, you are always receiving undefined.
You are mixing up two different implementation.
Either you use direct assignation.
var testA = new Array(4);
for (i = 0; i < 4; i += 1) {
this.currency = prompt('...', '');
testA[i] = this.currency;
}
Either you push new values into the array.
var testA = [];
for (i = 0; i < 4; i += 1) {
this.currency = prompt('...', '');
testA.push(this.currency);
}
You should use the second one, which is the most simple soluce.
testA[i] = this.currency OR testA.push(this.currency)
Use Modified function below
function Test() {
var testA = [];
for (i = 0; i < 4; i++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i] = this.currency; // use this.currency here if you
}
console.log(testA);
}
var index = new Test();

Perform a merge on two strings

I'm trying to build a collaborative doc editor and implement operational transformation. Imagine we have a string that is manipulated simultaneously by 2 users. They can only add characters, not remove them. We want to incorporate both of their changes.
The original string is: catspider
The first user does this: cat<span id>spider</span>
The second user does this: c<span id>atspi</span>der
I'm trying to write a function that will produce: c<span id>at<span id>spi</span>der</span>
The function I've written is close, but it produces c<span id>at<span i</span>d>spider</span> codepen here
String.prototype.splice = function(start, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start);
};
function merge(saved, working, requested) {
if (!saved || !working || !requested) {
return false;
}
var diffSavedWorking = createDiff(working, saved);
var diffRequestedWorking = createDiff(working, requested);
var newStr = working;
for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {
//splice does an insert `before` -- we will assume that the saved document characters
//should always appear before the requested document characters in this merger operation
//so we first insert requested and then saved, which means that the final string will have the
//original characters first.
if (diffRequestedWorking[i]) {
newStr = newStr.splice(i, diffRequestedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffRequestedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
if (diffSavedWorking[i]) {
newStr = newStr.splice(i, diffSavedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffSavedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
}
return newStr;
}
//arr1 should be the shorter array.
//returns inserted characters at their
//insertion index.
function createDiff(arr1, arr2) {
var diff = [];
var j = 0;
for (var i = 0; i < arr1.length; i++) {
diff[i] = "";
while (arr2[j] !== arr1[i]) {
diff[i] += arr2[j];
j++;
}
j++;
}
var remainder = arr2.substr(j);
if (remainder) diff[i] = remainder;
return diff;
}
function insertNatX(arr, length, pos) {
for (var j = 0; j < length; j++) {
arr.splice(pos, 0, "");
}
}
var saved = 'cat<span id>spider</span>';
var working = 'catspider';
var requested = 'c<span id>atspi</span>der';
console.log(merge(saved, working, requested));
Would appreciate any thoughts on a better / simpler way to achieve this.

Check if string contains substring without using indexOf - Javascript

My function is trying to check if string contains substring without use of indexOf or regex match or any standard JS methods.
Please check this jsfiddle: https://jsfiddle.net/09x4Lpj2/
var string1 = 'applegate';
var string2 = 'gate';
function containsString(string1, string2){
var j = 0;
var k = 0;
var contains = 'false';
var charArray1 = string1.split('');
var charArray2 = string2.split('');
for(var i = 0; i < charArray2.length; i++){
j = i;
if(charArray1[j++] != charArray2[k++]){
contains = 'false';
}else{
contains = 'true';
}
}
console.log(contains);
}
containsString(string1, string2);
This solution works only when the indexes are the same between the two strings (ex. applegate and apple). But will not work if the indexes are not the same (ex. applegate and gate). How do I manipulate the iterative values correctly so that the function returns true for both situations?
you can try this modified script of yours.
var string1 = 'applegate';
var string2 = 'gate';
var string3 = 'apple';
var string4 = 'leg';
var string5 = 'banana';
function containsString(string1, string2){
var charArray1 = string1.split('');
var charArray2 = string2.split('');
var match = 0;
// iterate from start of 1st string until length of 1st string minus length of 2nd string
// you don't need to iterate the last part that is not longer than 2nd string since it will be false
for(var i = 0; i < charArray1.length - charArray2.length + 1; i++){
// reset match counter on every iteration
match = 0;
// iterate the 2nd string
for(var j = 0; j < charArray2.length; j++){
// compare corresponding char location
if(charArray1[i+j] == charArray2[j]){
match++;
// just to check in console
console.log(i, j, match, charArray1[i+j], charArray2[j]);
} else {
// just to check in console
console.log(i, j, match, charArray1[i+j], charArray2[j]);
// if not match, just skip current check
break;
}
// if match already found, stop the checks, and return true
if(match == charArray2.length){
return true;
}
}
}
// match not found until end of iteration
return false;
}
console.log(containsString(string1, string2));
console.log(containsString(string1, string3));
console.log(containsString(string1, string4));
console.log(containsString(string1, string5)); // haystack does not contain needle
console.log(containsString(string4, string1)); // haystack is shorter than needle
Welcome to SO.
Regex can be used.. Unless even that is also prohibited..
function containsString(string1, string2){
console.log(string1.match(string2) != null ? "Yes" : "No");
}
Regex
This code has a logical problem,Only to determine whether the last character of A is equal to the corresponding character of B,Maybe the following code is what you want,add a line of code.
var string1 = 'applegate';
var string2 = 'gate';
function containsString(string1, string2){
var j = 0;
var k = 0;
var contains = 'false';
var charArray1 = string1.split('');
var charArray2 = string2.split('');
for(var i = 0; i < charArray2.length; i++){
j = i;
if(charArray1[j++] != charArray2[k++]){
contains = 'false';
break;
}else{
contains = 'true';
}
}
console.log(contains);
}
Check this without using any inbuilt functions
function subSearch(long,short){
var count = 0
for(i = 0;i < long.length; i++){
for(j = 0;j < short.length; j++){
if(short[j] != long[i + j]){
break;
}
if((j+1) == short.length){
count++;
}
}
}
return count;
}

Check series of checkboxes according to string

I have group of checkboxes nearly equals to 100 all are with name checkbox1...checkbox1oo. I am getting a string from database in the bit format. Now I need to check checkboxes using for loop according to everyposition for string..
just taking example. String is 10010. that means I have to select checkbox 1st AND 4th. Hows it will be possible.
for (i=1;i<=5;i++)
{
check every position of sting==1
than document.formname.checkbox[i]==checked.
}
I wish to do something like that.
for( var i = 0, l = string.length ; i < l ; i++ ) {
if( string.charAt(i) === "1" ) {
document.forms[formname]['checkbox' + i].checked = true;
}
}
where string is the string from your database, and formname is the id of the form you're manipulating
Get all the tags, loop through, get check boxes, build the string.
var elements = document.getElementsByTagName('input');
var str = "010101";
for(var i = 0; i< elements.length; i++) {
if (elements[i].type == "checkbox") {
var index = +(elements[i].name.match(/\d+/g)[0]); // get index
elements[i].checked = !!(+str.charAt(index -1));
}
}
http://jsfiddle.net/UMuxP/
!!(+str.charAt(index -1))
could easily be:
str.charAt(index -1) === "1"

Categories

Resources