How to determine where's the place of number in a string - javascript

How to determine after which comma is the place of the number 13 in a string with commas(,) with JS?
For example:
string - testtest,teststestatestb,testj
The letter "s" is the 13-th letter and it's after the first comma.

I'm not sure if I understand your Question. But here is a possible solution:
function count_commas_to_position(string,position) {
return string.substring(0,position).replace(/[^,]/g,'').length
}
// if you don't want to count commas on `position`
function count_commas_to_position(string,position) {
return string.substring(0,position-1).replace(/[^,]/g,'').length
}
var string = "testtest,teststestatestb,testj"
var comma_count = count_commas_to_position(string,13);

You need to split string in array with ',' and then check for each string length using loop in correspond to array length.
like
var str="testtest,teststestatestb,testj";
var a1 = new Array();
a1=str.split(",");
for(var i=0;i < a1.length ; i++ )
{
if(a1[i].length > 13)
{
//get 13th index of the word.
}
}

Try
a.indexOf('s',a.indexOf(','))
write a method
function abc(){
var a = "esttestte,ststestatestbtestj"
var c = a.indexOf(',')
if (c==-1)
alert("',' is not present ")
else{
var b =a.indexOf('s',c)
if (b==-1)
alert("'s' is not present after ','")
else
alert("position of 's' after ',' is "+(b+1) )
}
}

Related

Js function that returns a matching letter from 2 strings

Function that returns the first letter that is present in both strings that a user submits via
an input type text, the strings are separated with a comma. For example:aaaaa,bbbbba--> the matching letter is 'a'because is present in both strings
Sorry for some italian names but i code in italian
I'm not sure how to continue, i have a for to go throught both strings, but i'm not sure if it's correct
function Ripetizione() {
var rip = document.getElementById("string").value;
if (rip.indexOf(",") == -1) { //check to see if the comma is not present
alert("Non c'è nessuna virgola");
return;
}
var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma
for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string
}
for (k = 0; i <= stringa2.lenght; k++) { //same for the string2
}
}
Ripetizione()
You need not loop the second string.. Just check for index of the element => 0 , while looping through each element of first string part. And return the value..
Always prefer functional over imperative programming.Use Array#find
function getCommonLetter(str){
const [stringA, stringB]=str.split(',');
return Array.from(stringB).find(val => stringA.includes(val));
}
console.log(getCommonLetter('ab,ba'))
console.log(getCommonLetter('ads,bsd'))
console.log(getCommonLetter('aaa,bbc'))
function Ripetizione() {
var rip=document.getElementById("string").value;
if (rip.indexOf(",")==-1){
alert("Non c'è nessuna virgola");
return;
}
var stringa1=rip.substr(0,rip.indexOf(","));
var stringa2=rip.substr(rip.indexOf(",")+1,rip.length-(stringa1.length+1));
return search(stringa1, stringa2);
}
function search(a, b){
for(var i=0; i<a.length;i++){
for(var j=0;j<b.length;j++){
if(a[i] == b[j]){
return a[i];
}
}
}
}
We can do it using Array#reduce and check for the presence of the matching chars using Array#includes.
The idea is to convert the strings into an array of string using Array#from then use the reduce function to match and accumulate the matched characters.
//returns the matching chars as an array
function Ripetizione(rip) {
//let rip=document.getElementById("string").value;
let strs = rip.split(",");
if (strs.length !== 2){ //check to see if the comma is not present
alert("Non c'è nessuna virgola");
return;
}
//converting strings to array to use reduce
let strOne = Array.from(strs[0]), strTwo = strs[1];
return strOne.reduce((acc,alpha)=> {
return !acc.includes(alpha) && strTwo.includes(alpha)?[alpha,...acc]:acc;
},[]).slice(0,1).toString();
}
console.log(Ripetizione("aaaaaab,bbbbba"));
console.log(Ripetizione("aaaaaa,bbbbba"));
console.log(Ripetizione("acccaaaa,bbbbba"));
console.log(Ripetizione("acccaaaa,bbbbcba"));
console.log(Ripetizione("dddddddd,bbbbba")); //return blank string
console.log(Ripetizione("ab,ba"));
function Ripetizione() {
var rip = document.getElementById("string").value;
if (rip.indexOf(",") == -1) { //check to see if the comma is not present
alert("Non c'è nessuna virgola");
return;
}
var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma
if (stringa1.length <= stringa2.length) {
stringa2 = stringa2.split('')
stringa1 = stringa1.split('')
for (i = 0; i <= stringa2.length; i++) { //for cycle to count the elements of the first string
if (stringa1.includes(stringa2[i])) {
console.log(stringa2[i]);
}
}
} else if (stringa1.length >= stringa2.length) {
stringa1 = stringa1.split('')
stringa2 = stringa2.split('')
for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string
if (stringa2.includes(stringa1[i])) {
console.log(stringa1[i]);
}
}
}
}
<input id="string" type="text">
|<button id="ok" onclick="Ripetizione()">done</button>
The following demo binds the change event to input. When a user enters text in input then clicks outside of input the function is called. The function uses split() and filter() and displays the result in an output. The function also removes any spaces and reports if there are no matches as well.
Demo
Details are commented in demo
var str = document.getElementById("string");
// This is an Event Handler
function ripZ(e) {
var result = document.getElementById('result');
var rip = this.value;
if (rip.indexOf(",") === -1) {
result.value = "Separate the two strings with a comma (no spaces).";
return;
}
// If there's a space remove it
var rip = rip.replace(/\s/g, '');
// Split the string at the comma making an array of two strings
var array = rip.split(',');
/*
Take each string and split them at each letter.
Now there's two arrays of letters
*/
var first = array[0].split('');
var second = array[1].split('');
/*
Loop through both arrays by using two for...of loops
*/
var match = first.filter(function(f, i) {
return second.indexOf(f) !== -1;
});
// Display results
if (match) {
result.innerHTML = `
The letter "${match[0]}" is the first match between both strings.`;
} else {
result.value = "There was no match."
}
return;
}
/*
This is an onevent property registered to the input
If a user types into the input then clicks outside of input
the Event Handler ripZ() is called.
*/
str.onchange = ripZ;
<input id='string'><button>GO</button><br>
<output id='result'></output>
If the input was "ab,ba", you sad that it should be return b so Code must be above in my openion :
function Ripetizione() {
// var rip=document.getElementById("string").value;
// if (rip.indexOf(",")==-1){
// alert("Non c'è nessuna virgola");
// return;
// }
// var stringa1=rip.substr(0,rip.indexOf(","));
// var stringa2=rip.substr(rip.indexOf(",")+1,rip.length-(stringa1.length+1));
var stringa1="ab";
var stringa2="ba";
for(var i=0; i<stringa2.length;i++){
for(var j=0;j<stringa1.length;j++){
if(stringa2.charAt(i) === stringa1.charAt(j)){
console.log(stringa2.charAt(i));
return;
}
}
}

How to make element in Array change its' place

I'm beginner in JS. I've tried to understand Caesar Cipher ROT13, but it was too complicated for me. So I've tried to write my own code. Here it is below:
function encrip() {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var str = "Ni Hao";
var string = str.toUpperCase();
for (var i = 0; i < string.length; i++) {
for (var k = 0; k < alphabet.length; k++) {
if(string.charAt(i) == alphabet[k]) {
/* console.log(string.charAt(i) + ' ' + alphabet.indexOf(alphabet[k])); */
}
}
}
}
encrip();
But I am stuck. How to do:
1. Get value from var str and then access to var alphabet , after change each letter from var str value to next 3 from alphabet (var str each element's current position would be changed) For example: Input: Ni Hao ==> output: QL KDR
2. Create universal code, I mean, not only for changing position by 3, but when I give value '5', each element would be changed by next 5 positions from alphabet. So output can be changed when I change its' value
I hope I explained everything clearly. Thanks everyone in advance for help!!
you can use the following function to encrypt english words, the 1st parameter is the string to encrypt and the 2nd for shifting
function encryp(str,pos){
var alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strUC=str.toUpperCase();
var enc="";
for(var i=0;i<strUC.length;i++){
if(strUC.charAt(i)!=" "){
enc+=alpha.charAt((alpha.indexOf(strUC.charAt(i))+pos)%26)
}
else{
enc+=" "
}
// in your case pos=3
}
return enc;
}
console.log(encryp("NiHao",3));
You don't need two for loops to do this. Iterate over the input string and find the index of each character in the alphabet array, if found add the shift to it to get the encrypted character.
To handle overflow use the modulus operator to cycle through the array.
Also I assume that you are not going use any special symbols to do the encryption.
function encrip(string, shift) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
string = string.toUpperCase();
let arr = [];
for (var i = 0; i < string.length; i++) {
let char = alphabet.indexOf(string[i]) !== -1 ? alphabet[(alphabet.indexOf(string[i]) %26) + shift] : " ";
arr.push(char);
}
let encryp = arr.join("");
console.log(encryp);
return encryp;
}
encrip("Ni Hao", 3);
First of all, instead of your inner for loop scanning the whole alphabet array, you can use the built-in function indexOf:
alphabet.indexOf('K') // returns 10
Secondly, you'll want to build up your enciphered string in a separate variable. For each letter, get the index of that letter in the alphabet, add your cipher offset parameter to that index and add the resulting letter from the alphabet to your new string. An important step is that when you add to the index of the letter, you want to make sure the resulting index is within range for the alphabet array. You can do that using the % (modulo) operator, which will wrap high values back round to the start of the array. In full:
function encipher(input, offset) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var str = input.toUpperCase();
var result = '';
for (var i = 0; i < str.length; i++) {
letterIndex = alphabet.indexOf(str.charAt(i));
if (letterIndex === -1) {
result += str[i]; // if the letter isn't found in the alphabet, add it to the result unchanged
continue;
}
cipheredIndex = (letterIndex + offset) % alphabet.length; // wrap index to length of alphabet
result += alphabet[cipheredIndex];
}
console.log(result);
}
encipher('Ni Hao', 5); // output: 'SN MFT'

Regex split on comma don't split on comma between double quotes [duplicate]

I'm looking for [a, b, c, "d, e, f", g, h]to turn into an array of 6 elements: a, b, c, "d,e,f", g, h. I'm trying to do this through Javascript. This is what I have so far:
str = str.split(/,+|"[^"]+"/g);
But right now it's splitting out everything that's in the double-quotes, which is incorrect.
Edit: Okay sorry I worded this question really poorly. I'm being given a string not an array.
var str = 'a, b, c, "d, e, f", g, h';
And I want to turn that into an array using something like the "split" function.
Here's what I would do.
var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
/* will match:
(
".*?" double quotes + anything but double quotes + double quotes
| OR
[^",\s]+ 1 or more characters excl. double quotes, comma or spaces of any kind
)
(?= FOLLOWED BY
\s*, 0 or more empty spaces and a comma
| OR
\s*$ 0 or more empty spaces and nothing else (end of string)
)
*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);
regex: /,(?=(?:(?:[^"]*"){2})*[^"]*$)/
const input_line = '"2C95699FFC68","201 S BOULEVARDRICHMOND, VA 23220","8299600062754882","2018-09-23"'
let my_split = input_line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/)[4]
Output:
my_split[0]: "2C95699FFC68",
my_split[1]: "201 S BOULEVARDRICHMOND, VA 23220",
my_split[2]: "8299600062754882",
my_split[3]: "2018-09-23"
Reference following link for an explanation: regexr.com/44u6o
Here is a JavaScript function to do it:
function splitCSVButIgnoreCommasInDoublequotes(str) {
//split the str first
//then merge the elments between two double quotes
var delimiter = ',';
var quotes = '"';
var elements = str.split(delimiter);
var newElements = [];
for (var i = 0; i < elements.length; ++i) {
if (elements[i].indexOf(quotes) >= 0) {//the left double quotes is found
var indexOfRightQuotes = -1;
var tmp = elements[i];
//find the right double quotes
for (var j = i + 1; j < elements.length; ++j) {
if (elements[j].indexOf(quotes) >= 0) {
indexOfRightQuotes = j;
break;
}
}
//found the right double quotes
//merge all the elements between double quotes
if (-1 != indexOfRightQuotes) {
for (var j = i + 1; j <= indexOfRightQuotes; ++j) {
tmp = tmp + delimiter + elements[j];
}
newElements.push(tmp);
i = indexOfRightQuotes;
}
else { //right double quotes is not found
newElements.push(elements[i]);
}
}
else {//no left double quotes is found
newElements.push(elements[i]);
}
}
return newElements;
}
Here's a non-regex one that assumes doublequotes will come in pairs:
function splitCsv(str) {
return str.split(',').reduce((accum,curr)=>{
if(accum.isConcatting) {
accum.soFar[accum.soFar.length-1] += ','+curr
} else {
accum.soFar.push(curr)
}
if(curr.split('"').length % 2 == 0) {
accum.isConcatting= !accum.isConcatting
}
return accum;
},{soFar:[],isConcatting:false}).soFar
}
console.log(splitCsv('asdf,"a,d",fdsa'),' should be ',['asdf','"a,d"','fdsa'])
console.log(splitCsv(',asdf,,fds,'),' should be ',['','asdf','','fds',''])
console.log(splitCsv('asdf,"a,,,d",fdsa'),' should be ',['asdf','"a,,,d"','fdsa'])
This works well for me. (I used semicolons so the alert message would show the difference between commas added when turning the array into a string and the actual captured values.)
REGEX
/("[^"]*")|[^;]+/
var str = 'a; b; c; "d; e; f"; g; h; "i"';
var array = str.match(/("[^"]*")|[^;]+/g);
alert(array);
Here's the regex we're using to extract valid arguments from a comma-separated argument list, supporting double-quoted arguments. It works for the outlined edge cases. E.g.
doesn't include quotes in the matches
works with white spaces in matches
works with empty fields
(?<=")[^"]+?(?="(?:\s*?,|\s*?$))|(?<=(?:^|,)\s*?)(?:[^,"\s][^,"]*[^,"\s])|(?:[^,"\s])(?![^"]*?"(?:\s*?,|\s*?$))(?=\s*?(?:,|$))
Proof: https://regex101.com/r/UL8kyy/3/tests (Note: currently only works in Chrome because the regex uses lookbehinds which are only supported in ECMA2018)
According to our guidelines it avoids non-capturing groups and greedy matching.
I'm sure it can be simplified, I'm open to suggestions / additional test cases.
For anyone interested, the first part matches double-quoted, comma-delimited arguments:
(?<=")[^"]+?(?="(?:\s*?,|\s*?$))
And the second part matches comma-delimited arguments by themselves:
(?<=(?:^|,)\s*?)(?:[^,"\s][^,"]*[^,"\s])|(?:[^,"\s])(?![^"]*?"(?:\s*?,|\s*?$))(?=\s*?(?:,|$))
I almost liked the accepted answer, but it didn't parse the space correctly, and/or it left the double quotes untrimmed, so here is my function:
/**
* Splits the given string into components, and returns the components array.
* Each component must be separated by a comma.
* If the component contains one or more comma(s), it must be wrapped with double quotes.
* The double quote must not be used inside components (replace it with a special string like __double__quotes__ for instance, then transform it again into double quotes later...).
*
* https://stackoverflow.com/questions/11456850/split-a-string-by-commas-but-ignore-commas-within-double-quotes-using-javascript
*/
function splitComponentsByComma(str){
var ret = [];
var arr = str.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g);
for (let i in arr) {
let element = arr[i];
if ('"' === element[0]) {
element = element.substr(1, element.length - 2);
} else {
element = arr[i].trim();
}
ret.push(element);
}
return ret;
}
console.log(splitComponentsByComma('Hello World, b, c, "d, e, f", c')); // [ 'Hello World', 'b', 'c', 'd, e, f', 'c' ]
Parse any CSV or CSV-String code based on TYPESCRIPT
public parseCSV(content:string):any[string]{
return content.split("\n").map(ar=>ar.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(refi=>refi.replace(/[\x00-\x08\x0E-\x1F\x7F-\uFFFF]/g, "").trim()));
}
var str='"abc",jkl,1000,qwerty6000';
parseCSV(str);
output :
[
"abc","jkl","1000","qwerty6000"
]
I know it's a bit long, but here's my take:
var sample="[a, b, c, \"d, e, f\", g, h]";
var inQuotes = false, items = [], currentItem = '';
for(var i = 0; i < sample.length; i++) {
if (sample[i] == '"') {
inQuotes = !inQuotes;
if (!inQuotes) {
if (currentItem.length) items.push(currentItem);
currentItem = '';
}
continue;
}
if ((/^[\"\[\]\,\s]$/gi).test(sample[i]) && !inQuotes) {
if (currentItem.length) items.push(currentItem);
currentItem = '';
continue;
}
currentItem += sample[i];
}
if (currentItem.length) items.push(currentItem);
console.log(items);
As a side note, it will work both with, and without the braces in the start and end.
This takes a csv file one line at a time and spits back an array with commas inside speech marks intact. if there are no speech marks detected it just .split(",")s as normal... could probs replace that second loop with something but it does the job as is
function parseCSVLine(str){
if(str.indexOf("\"")>-1){
var aInputSplit = str.split(",");
var aOutput = [];
var iMatch = 0;
//var adding = 0;
for(var i=0;i<aInputSplit.length;i++){
if(aInputSplit[i].indexOf("\"")>-1){
var sWithCommas = aInputSplit[i];
for(var z=i;z<aInputSplit.length;z++){
if(z !== i && aInputSplit[z].indexOf("\"") === -1){
sWithCommas+= ","+aInputSplit[z];
}else if(z !== i && aInputSplit[z].indexOf("\"") > -1){
sWithCommas+= ","+aInputSplit[z];
sWithCommas.replace(new RegExp("\"", 'g'), "");
aOutput.push(sWithCommas);
i=z;
z=aInputSplit.length+1;
iMatch++;
}
if(z === aInputSplit.length-1){
if(iMatch === 0){
aOutput.push(aInputSplit[z]);
}
iMatch = 0;
}
}
}else{
aOutput.push(aInputSplit[i]);
}
}
return aOutput
}else{
return str.split(",")
}
}
Use the npm library csv-string to parse the strings instead of split: https://www.npmjs.com/package/csv-string
This will handle the empty entries
Something like a stack should do the trick. Here I vaguely use marker boolean as stack (just getting my purpose served with it).
var str = "a,b,c,blah\"d,=,f\"blah,\"g,h,";
var getAttributes = function(str){
var result = [];
var strBuf = '';
var start = 0 ;
var marker = false;
for (var i = 0; i< str.length; i++){
if (str[i] === '"'){
marker = !marker;
}
if (str[i] === ',' && !marker){
result.push(str.substr(start, i - start));
start = i+1;
}
}
if (start <= str.length){
result.push(str.substr(start, i - start));
}
return result;
};
console.log(getAttributes(str));
jsfiddle setting image code output image
The code works if your input string in the format of stringTocompare.
Run the code on https://jsfiddle.net/ to see output for fiddlejs setting.
Please refer to the screenshot.
You can either use split function for the same for the code below it and tweak the code according to you need.
Remove the bold or word with in ** from the code if you dont want to have comma after split attach=attach**+","**+actualString[t+1].
var stringTocompare='"Manufacturer","12345","6001","00",,"Calfe,eto,lin","Calfe,edin","4","20","10","07/01/2018","01/01/2006",,,,,,,,"03/31/2004"';
console.log(stringTocompare);
var actualString=stringTocompare.split(',');
console.log("Before");
for(var i=0;i<actualString.length;i++){
console.log(actualString[i]);
}
//var actualString=stringTocompare.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
for(var i=0;i<actualString.length;i++){
var flag=0;
var x=actualString[i];
if(x!==null)
{
if(x[0]=='"' && x[x.length-1]!=='"'){
var p=0;
var t=i;
var b=i;
for(var k=i;k<actualString.length;k++){
var y=actualString[k];
if(y[y.length-1]!=='"'){
p++;
}
if(y[y.length-1]=='"'){
flag=1;
}
if(flag==1)
break;
}
var attach=actualString[t];
for(var s=p;s>0;s--){
attach=attach+","+actualString[t+1];
t++;
}
actualString[i]=attach;
actualString.splice(b+1,p);
}
}
}
console.log("After");
for(var i=0;i<actualString.length;i++){
console.log(actualString[i]);
}
[1]: https://i.stack.imgur.com/3FcxM.png
I solved this with a simple parser.
It simply goes through the string char by char, splitting off a segment when it finds the split_char (e.g. comma), but also has an on/off flag which is switched by finding the encapsulator_char (e.g. quote). It doesn't require the encapsulator to be at the start of the field/segment (a,b","c,d would produce 3 segments, with 'b","c' as the second), but it should work for a well formed CSV with escaped encapsulator chars.
function split_except_within(text, split_char, encapsulator_char, escape_char) {
var start = 0
var encapsulated = false
var fields = []
for (var c = 0; c < text.length; c++) {
var char = text[c]
if (char === split_char && ! encapsulated) {
fields.push(text.substring(start, c))
start = c+1
}
if (char === encapsulator_char && (c === 0 || text[c-1] !== escape_char) )
encapsulated = ! encapsulated
}
fields.push(text.substring(start))
return fields
}
https://jsfiddle.net/7hty8Lvr/1/
const csvSplit = (line) => {
let splitLine = [];
var quotesplit = line.split('"');
var lastindex = quotesplit.length - 1;
// split evens removing outside quotes, push odds
quotesplit.forEach((val, index) => {
if (index % 2 === 0) {
var firstchar = (index == 0) ? 0 : 1;
var trimmed = (index == lastindex)
? val.substring(firstchar)
: val.slice(firstchar, -1);
trimmed.split(",").forEach(v => splitLine.push(v));
} else {
splitLine.push(val);
}
});
return splitLine;
}
this works as long as quotes always come on the outside of values that contain the commas that need to be excluded (i.e. a csv file).
if you have stuff like '1,2,4"2,6",8'
it will not work.
Assuming your string really looks like '[a, b, c, "d, e, f", g, h]', I believe this would be 'an acceptable use case for eval():
myString = 'var myArr ' + myString;
eval(myString);
console.log(myArr); // will now be an array of elements: a, b, c, "d, e, f", g, h
Edit: As Rocket pointed out, strict mode removes eval's ability to inject variables into the local scope, meaning you'd want to do this:
var myArr = eval(myString);
I've had similar issues with this, and I've found no good .net solution so went DIY. NOTE: This was also used to reply to
Splitting comma separated string, ignore commas in quotes, but allow strings with one double quotation
but seems more applicable here (but useful over there)
In my application I'm parsing a csv so my split credential is ",". this method I suppose only works for where you have a single char split argument.
So, I've written a function that ignores commas within double quotes. it does it by converting the input string into a character array and parsing char by char
public static string[] Splitter_IgnoreQuotes(string stringToSplit)
{
char[] CharsOfData = stringToSplit.ToCharArray();
//enter your expected array size here or alloc.
string[] dataArray = new string[37];
int arrayIndex = 0;
bool DoubleQuotesJustSeen = false;
foreach (char theChar in CharsOfData)
{
//did we just see double quotes, and no command? dont split then. you could make ',' a variable for your split parameters I'm working with a csv.
if ((theChar != ',' || DoubleQuotesJustSeen) && theChar != '"')
{
dataArray[arrayIndex] = dataArray[arrayIndex] + theChar;
}
else if (theChar == '"')
{
if (DoubleQuotesJustSeen)
{
DoubleQuotesJustSeen = false;
}
else
{
DoubleQuotesJustSeen = true;
}
}
else if (theChar == ',' && !DoubleQuotesJustSeen)
{
arrayIndex++;
}
}
return dataArray;
}
This function, to my application taste also ignores ("") in any input as these are unneeded and present in my input.

Append number to a comma separated list

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?
Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.
If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}
You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

how to parse string to int in javascript

i want int from string in javascript how i can get them from
test1 , stsfdf233, fdfk323,
are anyone show me the method to get the integer from this string.
it is a rule that int is always in the back of the string.
how i can get the int who was at last in my string
var s = 'abc123';
var number = s.match(/\d+$/);
number = parseInt(number, 10);
The first step is a simple regular expression - \d+$ will match the digits near the end.
On the next step, we use parseInt on the string we've matched before, to get a proper number.
You can use a regex to extract the numbers in the string via String#match, and convert each of them to a number via parseInt:
var str, matches, index, num;
str = "test123and456";
matches = str.match(/\d+/g);
for (index = 0; index < matches.length; ++index) {
num = parseInt(matches[index], 10);
display("Digit series #" + index + " converts to " + num);
}
Live Example
If the numbers really occur only at the ends of the strings or you just want to convert the first set of digits you find, you can simplify a bit:
var str, matches, num;
str = "test123";
matches = str.match(/\d+/);
if (matches) {
num = parseInt(matches[0], 10);
display("Found match, converts to: " + num);
}
else {
display("No digits found");
}
Live example
If you want to ignore digits that aren't at the end, add $ to the end of the regex:
matches = str.match(/\d+$/);
Live example
var str = "stsfdf233";
var num = parseInt(str.replace(/\D/g, ''), 10);
var match = "stsfdf233".match(/\d+$/);
var result = 0; // default value
if(match != null) {
result = parseInt(match[0], 10);
}
Yet another alternative, this time without any replace or Regular Expression, just one simple loop:
function ExtractInteger(sValue)
{
var sDigits = "";
for (var i = sValue.length - 1; i >= 0; i--)
{
var c = sValue.charAt(i);
if (c < "0" || c > "9")
break;
sDigits = c + sDigits;
}
return (sDigits.length > 0) ? parseInt(sDigits, 10) : NaN;
}
Usage example:
var s = "stsfdf233";
var n = ExtractInteger(s);
alert(n);
This might help you
var str = 'abc123';
var number = str.match(/\d/g).join("");
Use my extension to String class :
String.prototype.toInt=function(){
return parseInt(this.replace(/\D/g, ''),10);
}
Then :
"ddfdsf121iu".toInt();
Will return an integer : 121
First positive or negative number:
"foo-22bar11".match(/-?\d+/); // -22
javascript:alert('stsfdf233'.match(/\d+$/)[0])
Global.parseInt with radix is overkill here, regexp extracted decimal digits already and rigth trimmed string

Categories

Resources