super remedial question that I just cant quite figure out (new to javascript).
I need to find a way to prompt for a string of text and then alert that string of text 3 times. I have tried the + sign in my alert but that would give me NaN or just an addition rather than just the string. For example if I input 2 it would return 6 rather than 222 which I need.
One way is to include strings in your concatenation:
alert(num+''+num+''+num);
Another is to convert the number to a string first:
var str = num.toString();
alert(str+str+str);
The whole thing would be:
var num = +prompt("Enter a number");
var str = num.toString();
alert(str + str + str);
Just include a string somewhere in between:
2+''+2+2
E.g.
var input = prompt('type something'), result = '';
for(var i = 0; i < 3; i++)
result += input;
console.log(result);
http://jsfiddle.net/35tp3/
Try this:
var number = 2, repeat = 3;
Array(repeat+1).join( number );
That will output "222"
If you want to add a space:
Array(repeat+1).join(" " + number).trim();
Which will output "2 2 2"
Related
I am a newbie on regular expression.
Could anybody suggest a regex to split string like below using Javascript?
The text I am dealing with should be split by a space character but sometimes it contains space within the text snippet like below:
Input:
SST+CONF!001 001 "407968017" "Projector Serial Number"
Desired output:
['SST+CONF!001', '001', '407968017', 'Projector Serial Number']
Please help!
Thank you!
This is longer than a one liner regex, but it converts the input to the format of the desired output you are looking for using split and regex:
var yourstring = 'SST+CONF!001 001 "407968017" "Projector Serial Number"';
// Regex to replace " with '
yourstring = yourstring.replace (/"/g,"'");
// Split where " " is
strArray = yourstring.split(" ");
var output = "[";
for (var i = 0; i < strArray.length; i++) {
if(i < 2){
strArray[i] = "'" + strArray[i] + "'";
}
if (i < 3){
output += strArray[i] + ", ";
}
else {
output += strArray[i] + " ";
}
}
// Regex to replace last character with ]
output = output.replace(/.$/, "]");
console.log(output);
Hope it helps!
Use the split function and use the regex provided inside it. It splits the array based on the regex. The regex finds all the space in the string
var a='SST+CONF!001 001 407968017 Projector Serial Number';
var b=a.split(/\s/g)
console.log(b)
My requirement is as follows. I have this example text:
html
9216143567 is the number and other one is 0112388908
Now I want a JS function which finds then numbers which are together and greater than 8 in number and adds html code around them like below
9216143567 is the number and other one is 0112388908
What is the right way to do this?
Try this. Takes string as input and gives HTML as output.
var abc = 'ei32eoeiq 9216143567 is the number and other one is 0112388908, 7878787878,deewodiwqodiwp 9898903232';
var splitArray = abc.match(/\d+/g);
for(var i = 0 ; i < splitArray.length; i++){
value = splitArray[i];
if(value.length>8) {
abc = abc.replace(value, ''+value+'');
}
}
console.log(abc);
document.getElementById("ans").innerHTML = abc;
<div id="ans"></div>
This can be solved with a regex: (\d{8,})[^\d]+(\d{8,})/g
It matches two matching groups, each of them wraps a number of at least 8 digits; where the two numbers are separated by at least one non-digit character.
let input = document.getElementById("input").innerHTML;
let regex = /(\d{8,})[^\d]+(\d{8,})/g;
let matches = regex.exec(input);
document.getElementById("ans").innerHTML = "OUTPUT: The first num is " + matches[1] + " and the second is " + matches[2];
<div id="input">
INPUT: 9216143567 is the number and other one is 0112388908
</div><br>
<div id="ans"></div>
Edit:
If you want to extract a dynamic number of numbers, you can use a simpler regex, \d{8,}. I've also modified the code so it replaces the original number with a URL that directs to it.
let input = document.getElementById("input").innerHTML;
let regex = /\d{8,}/g;
let match;
let matches_array = [];
while (match = regex.exec(input)) {
matches_array.push(match);
}
for (let i = 0; i < matches_array.length; i++) {
let tmp = '' + matches_array[i] + '';
input = input.replace(new RegExp(matches_array[i], "g"), tmp);
}
document.getElementById("ans").innerHTML = input;
<div id="input">
9216143567 is the number and other one is 0112388908 and the third is 1234567890
</div><br>
<div id="ans"></div>
How do we replace last character of a string?
SetCookie('pre_checkbox', "111111111111 11 ")
checkbox_data1 = GetCookie('pre_checkbox');
if(checkbox_data1[checkbox_data1.length-1]==" "){
checkbox_data1[checkbox_data1.length-1]= '1';
console.log(checkbox_data1+"after");
}
out put on console : 111111111111 11 after
Last character was not replaced by '1' dont know why
also tried : checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-1), "1");
could some one pls help me out
Simple regex replace should do what you want:
checkbox_data1 = checkbox_data1.replace(/.$/,1);
Generic version:
mystr = mystr.replace(/.$/,"replacement");
Remember that just calling str.replace() doesn't apply the change to str unless you do str = str.replace() - that is, apply the replace() function's return value back to the variable str
use regex...
var checkbox_data1 = '111111111111 11 ';
checkbox_data1.replace(/ $/,'$1');
console.log(checkbox_data1);
This will replace the last space in the string.
You have some space in our string please try it
checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-4), "1 ");
then add the space in
console.log(checkbox_data1+" after");
This is also a way, without regexp :)
var string = '111111111111 11 ';
var tempstr = '';
if (string[string.length - 1] === ' ') {
for (i = 0; i < string.length - 1; i += 1) {
tempstr += string[i];
}
tempstr += '1';
}
You can try this,
var checkbox_data1=checkbox_data1.replace(checkbox_data1.slice(-1),"+");
This will replace the last character of Your string with "+".
As Rob said, strings are immutable. Ex:
var str = "abc";
str[0] = "d";
console.log(str); // "abc" not "dbc"
You could do:
var str = "111 ";
str = str.substr(0, str.length-1) + "1"; // this makes a _new_ string
Is there a possibility to wrap each character in Javascript and prepend zero's if its less then X digits?
What i get/have:
var votes = 2;
//or
var votes = 123;
//or
var votes = 4321;
what it should to look like:
<span>0</span><span>0</span><span>0</span><span>2</span>
//or
<span>0</span><span>1</span><span>2</span><span>3</span>
//or
<span>4</span><span>3</span><span>2</span><span>1</span>
so the result should be a number with four digits.
here's a tricky version:
var votes = 123;
("0000" + votes).slice(-4); /* 0123 */
thus, to wrap each digit in a <span> you could fetch each digit with $.map and wrap it into its own element, like in this example fiddle: http://jsfiddle.net/cZAWj/
var votes = 973;
$.map(("0000" + votes).slice(-4), function(digit) {
$('<span/>', { text : digit }).appendTo($('body'));
});
Firstly, make it look like a string and pad it...
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Then you can iterate over it and add a span around each number. Then write the markup out as the .html of the parent element.
Well one way to do it would be to convert the number to a string and pre-append 0 until we reach the desired length.
So if you want X digits:
var strNb = "" + nb;
while (strNb.length < X){
strNb = "0" + strNb
}
function formatNumber(d, x) {
var l = String(d).length;
return (l<x?(Array(x-l).join('0') + d):String(d)).replace(/\d/g,"<span>$&</span>");
}
I have string looking like this:
01
02
03
99
I'd like to parse these to make them into strings like:
1. 2. 3. 99. etc.
The numbers are a maximum of 2 characters. Also I have to parse some more numbers later in the source string so I would like to learn the substring equivalent in javascript. Can someone give me advice on how I can do. Previously I had been doing it in C# with the following:
int.Parse(RowKey.Substring(0, 2)).ToString() + "."
Thanks
Why, parseInt of course.
// Add 2 until end of string
var originalA = "01020399";
for (var i = 0; i < originalA.length; i += 2)
{
document.write(parseInt(originalA.substr(i, 2), 10) + ". ");
}
// Split on carriage returns
var originalB = "01\n02\n03\n99";
var strArrayB = originalB.split("\n");
for (var i = 0; i < strArrayB.length; i++)
{
document.write(parseInt(strArrayB[i], 10) + ". ");
}
// Replace the leading zero with regular expressions
var originalC = "01\n02\n03\n99";
var strArrayC = originalC.split("\n");
var regExpC = /^0/;
for (var i = 0; i < strArrayC.length; i++)
{
document.write(strArrayC[i].replace(regExpC, "") + ". ");
}
The other notes are that JavaScript is weakly typed, so "a" + 1 returns "a1". Additionally, for substrings you can choose between substring(start, end) and substr(start, length). If you're just trying to pull a single character, "abcdefg"[2] will return "c" (zero-based index, so 2 means the third character). You usually won't have to worry about type-casting when it comes to simple numbers or letters.
http://jsfiddle.net/mbwt4/3/
use parseInt function.
parseInt(09) //this will give you 9
var myString = parseInt("09").toString()+". "+parseInt("08").toString();
string = '01\n02\n03\n99';
array = string.split('\n');
string2 = '';
for (i = 0; i < array.length; i++) {
array[i] = parseInt(array[i]);
string2 += array[i] + '. ';
}
document.write(string2);
var number = parseFloat('0099');
Demo
Substring in JavaScript works like this:
string.substring(from, to);
where from is inclusive and to is exclusive. You can also use slice:
string.slice(from, to)
where from is inclusive and to is exclusive. The difference between slice and substring is with slice you can specify negative numbers. For example, from = -1 indicates the last character. from(-1, -3) would give you the last 2 characters of the string.
With both methods if you don't specify end then you will get all the characters to the end.
Paul
Ii they are always 2 digits how about;
var s = "01020399";
var result = []
for (var i = 0; i < s.length; i+=2)
result.push(parseInt(s.substr(i, 2), 10) + ".")
alert( result[2] ) // 3.
alert( result.join(" ") ) // 1. 2. 3. 99.