My textfield has this value:
"1
2 2
3
4 4
5 a
6
7
8
"
When I split it by "\n" I get:
["1", "2 2", "3", "4 4", "5 a", "6", "7", "8", ""]
I want to delete the last element. I'm doing this:
$('#textArrayId').val().replace($('#textArrayId').val().split("\n")[$('#textArrayId').val().split("\n").length - 1], "")
And I can't get it to delete. What to do?
I want to do this with string operations, not array operations.
To remove the last line, use this
var lines = $('#textArrayId').val().split("\n");
var withoutLastLine = lines.slice(0, -1).join("\n");
$('#textArrayId').val(withoutLastLine);
Or if you want to remove the last line without whitespace:
var lines = $.trim($('#textArrayId').val()).split("\n");
var withoutLastLine = lines.slice(0, -1).join("\n");
$('#textArrayId').val(withoutLastLine);
To remove the last element of an array, use this expression to receive all elements but the last:
x.slice(0, -1)
It would be better to trim off the whitespace before splitting. That way you can handle input more robustly:
var lines = document.getElementById('textArrayId').value
.replace(/^\s+|\s+$/g,'').split(/\s+/);
The regex used in the split will also allow for input like:
1 2
3 4 5 6
7 8
Also note: No jQuery used ^_^
you can use the bounded array like a[7] to store the value from 1 to 8 .
Related
I have array in txt file and read this with
fs.readFileSync("./input.txt")
When i wrap it in console.log i get(since it is written in the file itself):
1 2 3
100 5000
I would have the array:
['1','2','3','100','5000']
Placement of the array in the input file should not change.
Suggest how to do it, please.
You can use regex to split words: \w+
let a = ` 1 2 3
100 5000 `;
console.log(a.match(/\w+/g))
To read your file and split it:
fs.readFileSync("./input.txt").match(/\w+/g)
One way, load it then, split by lines, then on each line split by space then flatten it, then filter out empty values.
let str = `1 2 3
100 5000 0`; // added 0 to show filter(Boolean) wont remove
console.log(str.split('\n').map(v => v.split(' ')).flat().filter(Boolean))
Result:
[
"1",
"2",
"3",
"100",
"5000",
"0"
]
You could split the string by a space, then filter out the falsy items in the resulting array.
const input = ` 1 2 3
100 5000 `;
let res = input.split(" ").filter(e => e.trim())
console.log(res)
For example, I have user input any string: "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. These are just examples, the user can input any string.
I want to map this to integer cardinality:
"1st" -> 0
"2nd" -> 1
"third" -> 2
"fourth" -> 3
"fifth" -> 4
"9999th" -> 9998
So I need some kind of function where:
function mapCardinality(input: string): number{
let numberResult:number = ??
return numberREesult;
}
and I can call it like this:
console.log(
mapCardinality("1st"), // print 0
mapCardinality("2nd"), // print 1
mapCardinality("third"), // print 2
mapCardinality("fourth"), // print 3
mapCardinality("fifth"), // print 4
mapCardinality("9999th") // print 9998
);
Just look it up in an array or parse it as number:
const mapCardinality = c => {
const pos = ["1st", "2nd", "third", "fourth", "fifth"].indexOf(c);
return pos === -1 ? parseInt(c, 10) - 1 : pos;
};
I'd first ask what are the suffixes for all of the inputs?
'nd', 'rd', 'st', 'th' (most numbers)
If they enter an integer with the above prefixes then you could write the following function:
const getInteger = input => input.slice(0, -2);
const num = getInteger('999th');
console.log(num); // prints "999"
If they enter the elongated variant, it becomes much more complex, especially when it comes to typos, lack of spaces, etc. One way could be to map single digit words ('one', 'two', etc), tens ('ten', 'twenty', etc'), hundreds, thousands, and so on instead of every number imaginable. I would then parse and find matching words to give a result. That being said it is still limiting. I would strongly suggest limiting user input formats. Why can't the user input an integer?
const cardinalDictionary = {
'zero': 0,
'one': 1,
...,
'twenty',
...,
'hundred': 100,
'thousand': 1000,
};
I have e scenario like this:
I need to build a jQuery function that takes a string as an input and update the string into another string.
The input can be one of these:
A="0"
A="0, 5" (basically can be "0, any_other_digits_different_from_0")
A="0, 58"
A="58" (basically any number that doesn't start with zero)
I want the function to updated to:
if input is option number one (A="0") update A="--"
if input is option number two (A="58") DO NOTHING, leave it A="58"
if input is option number three (A="0, 5" update to A="5"
if input is option number four (A="0, 58") update to A="58"
Option four can have more than two digits after "0, ".
It seems like this can be done by regex somehow but I am not being able to put anything together that can make it work. Any help is appreciated.
You could split the string and take the last value. If zero return '--'.
function getValue(a) {
return (+a.split(', ').pop() || '--').toString();
}
console.log(getValue("0")); // "--"
console.log(getValue("0, 5")); // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58")); // "58"
A proposal with a regular expression searching for last numbers
function getValue(a) {
return (+a.match(/\d+$/) || '--').toString();
}
console.log(getValue("0")); // "--"
console.log(getValue("0, 5")); // "5"
console.log(getValue("0, 58")); // "58"
console.log(getValue("58")); // "58"
This question already has answers here:
Ordinals in words javascript
(3 answers)
Closed 9 years ago.
Is there any inbuilt js/jquery function that converts 1 to first, 2 to second, 3 to third... etc.?
ex:
Num2Str(1); //returns first;
Num2str(2); //returns second;
I dont want to write a function for 100 numbers. Please help.
There is no inbuilt function for it.
I did write one for up to 99:
var special = ['zeroth','first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
var deca = ['twent', 'thirt', 'fort', 'fift', 'sixt', 'sevent', 'eight', 'ninet'];
function stringifyNumber(n) {
if (n < 20) return special[n];
if (n%10 === 0) return deca[Math.floor(n/10)-2] + 'ieth';
return deca[Math.floor(n/10)-2] + 'y-' + special[n%10];
}
// TEST LOOP SHOWING RESULTS
for (var i=0; i<100; i++) console.log(stringifyNumber(i));
DEMO: http://jsbin.com/AqetiNOt/1/edit
You could create a numberbuilder:
You will need to create a foolproof way to convert the single digits by power to a string.
1234 -->1(one)*10^3(thousand)+2(two)*10^2(hundred)+3(three)10(ten)+4(four)(one)
==> one thousand two hundred th irty four th
123456 --> one hundred tw enty three thousand four hundred fi fty six th
if you are wondering about the notation: I tried to split this up in the single decision steps you need to make
the rules for building repeat every three digits. The rest is up to you.
Oh and before I forget: there is only "3" exceptions to the th-rule. one, two and three.
I've done this in JavaScript but needless to say I can't just swap it over.
In Jscript I used this:
var estr = tx_val
index = 0
positions = []
while((index = estr.indexOf("e", index + 1)) != -1)
{
positions.push(index);
}
document.getElementById('ans6').innerHTML = "Locations of 'e' in string the are: "
+ positions;
I tried using the same logic with VBS terms, ie join, I also tried using InStr. I'm just not sure how to yank out that 'e'... Maybe I'll try replacing it with another character.
Here is what I tried with VBScript. I tried using InStr and replace to yank out the first occurance of 'e' in each loop and replace it with an 'x'. I thought that maybe this would make the next loop through give the location of the next 'e'. -- When I don't get a subscript out of range 'i' error, I only get one location back from the script and its 0.
(6) show the location of each occurence of the character "e" in the string "tx_val" in the span block with id="ans6"
countArr = array()
countArr = split(tx_val)
estr = tx_val
outhtml = ""
positions = array()
i=0
for each word in countArr
i= i+1
positions(i) = InStr(1,estr,"e",1)
estr = replace(estr,"e","x",1,1)
next
document.getElementById("ans6").innerHTML = "E is located at: " & positions
What can I do that is simpler than this and works? and thank you in advance, you all help a lot.
EDIT AGAIN: I finally got it working right. I'm not 100% how. But I ran through the logic in my head a few dozen times before I wrote it and after a few kinks it works.
local = ""
simon = tx_val
place=(InStr(1,simon,"e"))
i=(len(simon))
count = tx_val
do
local = (local & " " & (InStr((place),simon,"e")))
place = InStr((place+1),simon,"e")
count = (InStr(1,simon,"e"))
loop while place <> 0
document.getElementById("ans6").innerHTML= local
InStr has slightly different parameters to indexOf:
InStr([start, ]string, searchValue[, compare])
start: The index at which to start searching
string: The string to search
searchValue: The string to search for
Also note that Visual Basic indexes strings beginning at 1 so all the input and return index values are 1 more than the original JavaScript.
You can try split(). For example a simple string like this:
string = "thisismystring"
Split on "s", so we have
mystring = Split(string,"s")
So in the array mystring, we have
thi i my tring
^ ^ ^ ^
[0] [1] [2] [3]
All you have to do is check the length of each array item using Len(). For example, item 0 has length of 3 (thi), so the "s" is at position 4 (which is index 3). Take note of this length, and do for the next item. Item 1 has length of 1, so we add it to 4, to get 5, and so on.
#Update, here's an example using vbscript
thestring = "thisismystring"
delimiter="str"
mystring = Split(thestring,delimiter)
c=0
For i=0 To UBound(mystring)-1
c = c + Len(mystring(i)) + Len(delimiter)
WScript.Echo "index of s: " & c - Len(delimiter)
Next
Trial:
C:\test> cscript //nologo test.vbs
index of str is: 8