JS Replace multiple phrases [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to replace all %25 with % in puidInp, but only around words that mentioned in newPuidsValues.
I'm trying to solve it with loop, but it changes only one word at one time:
var newPuidsValues = ["banner.tracking_url", "banner.userN", "banner.alt"];
var puidInp = "tyhtyh%25banner.tracking_url%25tyhtyh%25banner.userN%25tyhtyh%25banner.userN%25tyhtyh%25banner.alt%25tyhtyh";
for (var h = 0; h < newPuidsValues.length; h++) {
const reg = new RegExp("\\D{1}\\d{2}" + newPuidsValues[h] + "\\D{1}\\d{2}", "g");
console.log(reg);
var puidOut = puidInp.replace(reg, "%" + newPuidsValues[h] + "%");
console.log(puidOut);
}

Make these small changes to your code:
Declare puidOut outside of your for-loop
Set the initial value of puidOut to puidInp
In the for-loop, use %25 in the RegExp you are creating to capture only the values you need to
In the for-loop, update puidOut in each iteration
Print when done
var newPuidsValues = ["banner.tracking_url", "banner.userN", "banner.alt"];
var puidInp = "tyhtyh%25banner.tracking_url%25tyhtyh%25banner.userN%25tyhtyh%25banner.userN%25tyhtyh%25banner.alt%25tyhtyh";
var puidOut = puidInp;
for (var h = 0; h < newPuidsValues.length; h++) {
const reg = new RegExp("%25" + newPuidsValues[h] + "%25", "g");
console.log(reg);
puidOut = puidOut.replace(reg, "%" + newPuidsValues[h] + "%");
}
console.log(puidOut);

Related

The following javascript code gives output 6 . How the code is executed? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
Why the output of the following code is not (1,2,3,4,5)?
var x = 0;
while (x < 6) {
x++;
}
document.write(x);
That is because you are only writing to the document once.
For this, you should probably use a for loop.
for (let x = 0+1; x < 5+1; x++) {
document.write(x);
}
This says x = 0 + 1 = 1 (so it starts at 0), then for every x > 5 + 1 (the +1 is so it ends at 5) do this, then add 1 to x.
Simply: x = 1, then when x is over 5, it will write to the document, then it will add 1 to x to continue the loop.
Each time the loop is repeated, the value in the x variable is updated.
x++ increases the value of x by one unit
And you write the final value
This example shows how to achieve this:
var x = 0;
let myArray = [];
while(x<6) {
++x; // We want x to start at 1
myArray.push(x) // Add the new value of x into the array
}
const string = '(' + myArray.join(',') + ')'; // Format the output string by joining the array in a csv format and wrapping with brackets.
document.write(string);

"X" is not defined - using "For loop" in Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm currently learning javascript loop and right now i'm trying to make an exemple using the "For" loop but as i'm trying it keep telling me "longString is not defined".
the result i'm trying to have is to print 6 A like this "AAAAAA"
here is the code:
var longString = A;
for (var longString = A; longstring < 6; longString = longString + A) {
console.log(longString);
}
i'm sure the solution is simple but as a totally beginner i can't figure out how to solve it.
You have a typo in your break condition:
var longString = "";
for (longString = "A"; longstring < 6; longString = longString + "A") {
// Note the lowercase 's' ^
}
console.log(longString);
Also, if you want to get the length of a string, you can use string.length:
longString.length < 6;
Does this what you want?
var str = ""
for (i = 0; i < 6; i++) {
str += "A"
}
console.log(str);
Try this, the below code prints "AAAAAA" in one line.
var longString = 'A'
var str = ''
for (var i = 0; i<6; i+=1){
str = longString + str
}
console.log(str)

Questions example phoneNumber [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am a student studying JavaScript.
It hasn't been long since I studied.
Example, createPhoneNumber
The length is up to 11 digits.
I wrote the code in question like this.
function createPhoneNumber(arr) {
let first = '(010)';
if(arr.length === 11){
return `(${arr.slice(0,3).join('')})${arr.slice(3,7).join('')}-${arr.slice(7,11).join('')}`;
}
return `${first}${arr.slice(0,4).join('')}-${arr.slice(4,8).join('')}`;
}
I think it's very messy code.
Is it better to add a new variable to make it shorter and simpler?
This can be done by Regex:
function createPhoneNumber(arr) {
let first = '(010)';
// the submatch (\D)? is intended to get an empty match when the length of arr is not 11
let reg = arr.length == 11 ? /(\d{3})(\d{4})(\d{4})/ : /(\D)?(\d{4})(\d{0,4})(\d{0,})/;
return arr.join('').replace(reg, (match, $1, $2, $3) => ($1 ? "(" + $1 + ")" : first) + $2 + "-" + $3);
}
console.log(createPhoneNumber([0,1,0,1,2,3,4,5,6,7,8]));
console.log(createPhoneNumber([1,2,3,4,5,6]));
console.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0,0,0,0,0]));
You want it shorter and simpler? This is subjective but I believe the following applies. Also, I wasn't sure if you misused your 11th digit in your function so... I made it work with 10.
function createPhoneNumber(arr) {
const arrL = arr.length;
let arrI = arrL - 4;
arr.splice(arrI, 0, "-");
arr.splice(arrI -= 3, 0, ")");
arr.splice(0, 0, arrL === 10 ? "(" : "(010");
return arr.join("");
}
If it's just a matter of readability, I suggest a few changes:
Export hard coded values to const.
Don't duplicate your code! like the complicated return you had.
It did look messy - do I decided to separate the number to 3 parts - 3 variables, and use 1 return
const PRE_FIRST = '(010)';
const FULL_NUMBER_LENGTH = 11;
function createPhoneNumber(arr) {
let isFullPhone = FULL_NUMBER_LENGTH === arr.length;
let first = isFullPhone ? arr.slice(0, 3).join('') : PRE_FIRST;
let second = (isFullPhone ? arr.slice(3, 7) : arr.slice(0, 4)).join('');
let third = (isFullPhone ? arr.slice(7, 11) : arr.slice(4, 8)).join('');
return `${first}-${second}-${third}`;
}

Would like javascript loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am adding subrows below a main row in an html table depending on which main row button is pushed. Here is some of the code:
if (document.getElementById("hdnSub0")) {
roz0 = document.getElementById("hdnSub0").value || 0;
}
...
if (document.getElementById("hdnSub10")) {
roz10 = document.getElementById("hdnSub10").value || 0;
}
nroz0 = parseInt(roz0, 10);
...
nroz10 = parseInt(roz10, 10);
if (intMainRow == 0) {
i = nroz0 + 2
};
...
if (intMainRow == 10) {
i = nroz0 + 2 + nroz1 + 1 + nroz2 + 1 + nroz3 + 1 + nroz4 + 1 + nroz5 + 1 + nroz6 + 1 + nroz7 + 1 + nroz8 + 1 + nroz9 + 1 + nroz10 + 1
};
row = table.insertRow(i);
I would like to write a loop especially for the if(intMainRow...) but I just haven't been able to it figure out.
So use a loop!
Consider getElementById("hdbSub" + i), where i is the loop variable incremented from 0..10. You can then use the loop (or an intermediate array) to go 0..x depending on the value of intMainRow.
For example:
// Because nroz0 + 2, but nrozOther + 1
// (You could also encode with an if/condition in the loop, but I
// feel like showing it this way.)
var incrs = [2,1,1,1,1,1,1,1,1,1,1];
// Running total (I use i/j/k only for loops.)
var total = 0;
// Will loop [0, intMainRow], an inclusive range, because of "<=".
// We loop once for each "field" and add the result in total.
for (var i = 0; i <= intMainRow; i++) {
var elm = document.getElementById("hdnSub" + i);
if (elm) {
// Add the value to the total along with
// the increment (+2/+1) for this index.
// (Each loop "adds" the next value to the equation
// written manually in the the original code.)
var v = parseInt(elm.value, 10) || 0;
total += v + incrs[i];
}
}
row = table.insertRow(total);

How to convert a string into a series of digits in Javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What would be a good way to turn a string into a series of digits in Javascript (I'm not talking about converting "0.5" into 0.5, but more "Hello" into 47392048)?
Any idea appreciated.
Thanks!
You can use the ASCII value of each letter:
"a letter".charCodeAt(0);
Ok, so given your comments, here is a (not widely tested) solution.
var str = "κόσμε 这是一条狗 é €";
$('#orig').after('<dd>' + str + '</dd>');
var result = "";
for (var i = 0, len = str.length, code, paddedCode; i < len; ++i) {
code = str[i].charCodeAt(0).toString();
paddedCode = code.length >= 8
? code
: new Array(8 - code.length + 1).join(0) + code; result += paddedCode;
result += paddedCode;
}
$('#nums').after('<dd>' + result + '</dd>');
var segments = result.match(/.{8}/g);
$.each(segments, function(k, v) {
$('#nums-segmented').after('<dd>' + v + '</dd>');
});
revertedString = '';
for (var i = 0, len = segments.length; i < len; i=i+2) {
revertedString += String.fromCharCode((segments[i] | 0));
}
$('#string').after('<dd>' + revertedString + '</dd>');
Run it at JSFiddle
The trick is to pad number and work with them as string when needed.

Categories

Resources