Swapping original string halves - javascript

Can I write a function that reads the content of an HTML textbox with id "message" and then writes into the HTML element with id "shuffled" with the value of original string with it's two halves swapped?
Examples:
"it" -> "ti"
"electric" -> "tricele"
"this laptop is lame" -> "op is lamethis lapt"

Yap it is possible, check this out:
var swap = function(str){
var half = Math.floor(str.length / 2);
return str.substr(half, str.length) + str.substr(0, half);
};
swap("electric"); // tricelec
Have fun :)

Related

Randomly choosing text with Javascript and displaying it

I'm having one of those days where I can't put into words what I'm trying to find. So, forgive me if this question has been asked before, if it has, I simply cannot find it.
If I have ten different lots of text, how can I randomly select one of them with Javascript, and display it.
The closest I've got is this:
var textArray = [
'Hello Fred',
'Hello Jimmy',
'Hello Terry'
];
var randomNumber = Math.floor(Math.random() * textArray.length);
audioElement.setAttribute('src', textArray[randomNumber]);
<p id="text-here">This is where I want the text to go</p>
I'm pretty sure this isn't close to what I need though.
I've tested it and it works just fine. Just enclose your array string values in double quotes and everything will work as you expected.
Here it is just setting the innerHTML value of p tag which is selected by id randomNumber and then set it with random text value of your array.
getElementById: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
innerHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
var textArray = [
"Hello I'm Fred1",
"Hello I'm Jimmy1",
"Hello I'm Terry1",
"Hello I'm Fred2",
"Hello I'm Jimmy2",
"Hello I'm Terry2",
"Hello I'm Fred3",
"Hello I'm Jimmy3",
"Hello I'm Terry3"
];
var randomNumber = Math.floor(Math.random() * textArray.length);
document.getElementById("randomNumber").innerHTML = textArray[randomNumber];
<p id="randomNumber"> </p>
Create a function to create random number
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
Call the function to get a random number which will act as the array index
var index = getRandomInt(9)
Now considering you have array as 'textArray' then you can write
var text = textArray[index]
Now to update the value in paragraph
document.getElementById("text-here").innerHTML=text;

What is the result of this javascript?

function getAttackString() {
var foo = "d322yvb34";
var bar = "x3nj4nhj9";
return "The code is: "+(foo.substr(3,foo.length-6))+(bar.substr(2);
}
I don't know what "+(foo.substr(3,foo.length-6))+(bar.substr(2)" means.
This takes a substring of 3 characters (foo.length-6) from foo starting at string index 3:
foo.substr(3,foo.length-6)
This takes the substring of all the characters in bar starting from string index 2:
bar.substr(2)
It then concatenates them.
The code you posted had a small typo. Here's the working code.
function getAttackString() {
var foo = "d322yvb34";
var bar = "x3nj4nhj9";
return "The code is: " + (foo.substr(3, foo.length - 6)) + bar.substr(2);
}
console.log(getAttackString())
You could take a look to the parameters of String#substr
str.substr(start[, length])
With this in mind, you could take all parts and do a manual work through of the single parts:
indices 012345678 action
string d322yvb34
foo.substr(3, foo.length - 6)
2yv foo.substr(3, 9 - 6)
indices 012345678
string x3nj4nhj9
nj4nhj9 bar.substr(2)
result 2yv nj4nhj9
And get the result
2yvnj4nhj9
Here is your full code explained.
// getAttackString is a function and the function name is "getAttackString"
function getAttackString() {
var foo = "d322yvb34";
var bar = "x3nj4nhj9";
//The substr() method extracts parts of a string, beginning at the character
//at the specified position, and returns the specified number of characters.
return "The code is: " + (foo.substr(3, foo.length - 6)) + bar.substr(2);
//Lets see what is going on here...
// 012345678
//foo = "d322yvb34"
//(foo.substr(3, foo.length - 6)) + bar.substr(2);
//Start from 3rd char (this means start at "2yvb34"),
//End at (foo.length - 6) i.e 9-6 = 3 = "2yv"
//Add bar.substr(2) bar = x3nj4nhj9
//Start from 2 i.e = "nj4nhj9"
//Now add "2yv" + "nj4nhj9" = "2yvnj4nhj9"
}
console.log(getAttackString())

Mask a portion of a String using RegExp

I'm trying to mask a portion of a string using JavaScript.
e.g. Mask second and third segment of credit-card number like this using regex:
4567 6365 7987 3783 → 4567 **** **** 3783
3457 732837 82372 → 3457 ****** 82372
I just want to keep the first 4 numbers and the last 5 characters.
This is my first attempt: /(?!^.*)[^a-zA-Z\s](?=.{5})/g
https://regex101.com/r/ZBi54c/2
You can try this:
var cardnumber = '4567 6365 7987 3783';
var first4 = cardnumber.substring(0, 4);
var last5 = cardnumber.substring(cardnumber.length - 5);
mask = cardnumber.substring(4, cardnumber.length - 5).replace(/\d/g,"*");
console.log(first4 + mask + last5);
You could slice the first four digits and apply a replacement for the rest.
console.log(
['4567 6365 7987 3783', '3457 732837 82372'].map(
s => s.slice(0, 4) + s.slice(4).replace(/\d(?=.* )/g, '*')
)
);
The answer apparently satisfies the OP. Here is another solution using only Regexes:
function starry(match, gr1, gr2, gr3) {
var stars = gr2.replace(/\d/g, '*');
return gr1 + " " + stars + " " + gr3;
}
function ccStarry(str) {
var rex = /(\d{4})\s(\d{4}\s\d{4}|\d{6})\s(\d{4}|\d{5})/;
if (rex.test(str))
return str.replace(rex, starry);
else return "";
}
var s1 = "4567 6365 7987 3783";
var s2 = "3457 732837 82372";
var s3 = "dfdfdf";
console.log(ccStarry(s1));
console.log(ccStarry(s2));
console.log(ccStarry(s3));
This ensures that the pattern matches before trying any replacements. For example, in the third test case, it returns an empty string. The pattern can be updated to match other credit card patterns besides the ones given in the question.
I would like to elaborate more on the answer from #Nina Scholz, I use .slice() in the following sample code for masking the variable in 2 condition.
Just a simple variable var n = '12345567890'
Array object
// Single number
var n = '601115558888';
var singleNumber = n.slice(0, 4) + n.slice(4, n.length -4).replace(/\d/g,'*') + n.slice(n.length -4);
console.log(singleNumber);
// array of object
var obj = [{
contacts_name: 'Jason',
contacts_num : '651231239991'
},
{
contacts_name: 'King',
contacts_num : '60101233321'
}];
// Mask for the middle number, showing the first4 number and last4 number
// and replace the rest number with *
var num = obj.map((element, index) =>
element.contacts_num.slice(0,4)
+ element.contacts_num.slice(4, element.contacts_num.length-4).replace(/\d/g, '*')
+ element.contacts_num.slice(element.contacts_num.length -4)
);
console.log(num);
If it's JavaScript doing the regex masking, you've already failed because JS should never need to know the original card number, except when you've just received it from the user and are sending it to the server for the first time, in which case you shouldn't be masking it anyway so the user can check for typos.
I can't really help you there, you've already failed in the worst way.
Server-side, if the number is already broken into spaces*, then one option is: (in PHP but the same idea applies to all)
$parts = explode(" ",$fullnumber);
$first = array_shift($parts);
$last = array_pop($parts);
$middle = implode(" ",$parts);
$mask = preg_replace("/\d/","*",$middle);
$result = "$first $mask $last";
* it shouldn't be

Replacing Stings, Index (-1) value must be greater or equal to zero.?

I'm getting the following error in my app's script when replacing strings in a template file to generate reports.
Index (-1) value must be greater or equal to zero.
The function is listed bellow.
/**
* Search a String in the document and replaces it with the generated newString, and sets it Bold
*/
function replaceString(doc, String, newString) {
var ps = doc.getParagraphs();
for(var i=0; i<ps.length; i++) {
var p = ps[i];
var text = p.getText();
//var text = p.editAsText();
if(text.indexOf(String) >= 0) {
//look if the String is present in the current paragraph
//p.editAsText().setFontFamily(b, c, DocumentApp.FontFamily.COMIC_SANS_MS);
p.editAsText().replaceText(String, newString);
// we calculte the length of the string to modify, making sure that is trated like a string and not another ind of object.
var newStringLength = newString.toString().length;
// if a string has been replaced with a NON empty space, it sets the new string to Bold,
Logger.log([newString,newStringLength]);
if (newStringLength > 0) {
// re-populate the text variable with the updated content of the paragraph
text = p.getText();
Logger.log(text);
p.editAsText().setBold(text.indexOf(newString), text.indexOf(newString) + newStringLength - 1, true);
}
}
}
}
When it errors out
[newString,newStringLength] = [ The Rev Levels are at ZGS 003 on the electric quality standard. The part has a current change to ZGS 005!,108]
Does anyone have any suggestions?
Thanks in advance,
Michael
You are not handling the case where the string isnt there. Thus indexOf returns -1 and you use that. Also dont use reserved words like String for variable names.

Insert space after certain character into javascript string

I'm working on a form and I'd like to mask the input of the phone numbers. The plugins what I found aren't okay for me since the area code could be 1 or 2 character long.
What I'd like to do is the following:
when the user types his number after the first two character the script inserts a space on keyup, then after the next three and later after every fourth character.
So when someone types 44444444444 then in the textbox appears 44 44 444 4444.
I must check the second group as well, and when someone types there for example 1, the the number must look like: 44 1 444 4444
Is any solution to do that?
You could do something like this:
http://jsfiddle.net/ffwAA/4/
Which applies this function to the string to get the desired formatting:
function formatCode(str){
var result = str;
str = str.replace(/\D+/g, "");
var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/);
if(m){
result = m[1] + " ";
if(m[2]) result += m[2] + " ";
if(m[3]) result += m[3] + " ";
if(m[4]){
result += m[4].split(/(\d{4})/).join(" ");
result = result.replace(/\s+/g, " ");
}
}
return result;
}
And using this jQuery to set it up:
function update(obj){
var val = obj.value;
var got = formatCode(val);
if(got != val)
obj.value = got;
}
var timer;
var prev_val = "";
$('#code').keyup(function(){
clearTimeout(timer);
// when adding numbers at the end of input, update at once
// don't want to update when editing in the middle of the string or removing parts of it
// because it would move the carret location to the end of input, and make it unusable
if(this.value.indexOf(prev_val) == 0){
update(this);
prev_val = this.value;
return;
}
prev_val = this.value;
// in other cases update 1 second after the changes are done
timer = setTimeout(update, 1000, this);
});
Have you tried the maskedInput plugin?
http://digitalbush.com/projects/masked-input-plugin/
I think it can solve your problem.
Hope this helps. Cheers

Categories