Hi my current string is shown:
082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456
24 6 digit numbers in total, notice the new lines between them.
I need this entire string to be broken down into an array such that [082759,078982,etc] is displayed and so that when calling:
console.log(array[0])
will output:
082759
NOTE: The '\n' method does not seem to work and when re-calling it [when within an array], e.g array[0], it outputs all the numbers.
The variable under which this data is derived from comes via:
var currentSku = $(this).attr('data-productsku')
So if this j-query has a specific string type then its probably something to do with this?
Because they have '\n' in-between, use split()
let arr = str.split('\n')
console.log(arr[0]);
If you're adding the digit on a new-line each time, you can use .split() method.
You have to pass the delimiter you want to split by; in your case, you use \n as that's how new-lines are escaped in Javascript. This will create an array of data.
Using the code below you can do like so:
let string = `082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456`;
let arr = string.split('\n');
console.log(arr[0]);
Try this code
var test = "082759 078982 074470 066839 062069 062068";
var arr = test.split(" ");
console.log(arr[0]);
console.log(arr[4]);
Tested code!
Note: There should be a space in between each number.
Next line solution is here
var test =
`082759
078982
074470
066839
062069
06206`;
var arr = test.split("\n");
console.log(arr[0]);
console.log(arr[4]);
If splitting using \n doesn't work then it might be that your string is using a different style of line ending. You can try \r or \r\n for instance.
array.split(/\n/)
or
array.split(\n)
Related
I have written the following console log to convert a list of [] to commas:
[Item 1][Item 2][Item 3][Item 4]
...
.split(/[[\]]{1,2}/);
but I am getting the following printed out:
,Item 1,Item 2,Item 3,Item 4,
when I am looking for:
Item 1,Item 2,Item 3,Item 4
I have tried a variety of different approaches but none provide me with the above last result.
You could use match instead of split and take directly the result array.
var string = '[Item 1][Item 2][Item 3][Item 4]',
parts = string.match(/[^\[\]]+/g);
console.log(parts);
Without going with regex, you could just slice it before splitting.
var str = "[Item 1][Item 2][Item 3][Item 4]";
var result = str.slice(1,-1).split`][`;
console.log(result);
The regex option would be:
var str = "[Item 1][Item 2][Item 3][Item 4]";
var result = str.match(/[\w ]+/g);
console.log(result);
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)
I have a number returned from the database
e.g.
329193914
What I would like to do it simply be able to just insert dashes every 3 characters.
e.g.
329-193-914
I was looking at regex, replace and slice , slice I had a hard time with as a lot of example are like f.value and i'm not passing in "this" (entire element)
if your number can be treated as a string:
var str = '329193914';
var arr = str.match(/.{3}/g); // => ['329', '193', '914']
var str2 = arr.join('-'); // => '329-193-914'
I have an array like ["one, two, three"].
I want to convert it to ["one","two","three"].
I was using split to do this like:
$var temp=["one, two, three"];
temp.split(", ");
This is giving me error. Any idea how to do this?
It's an array with one single value, and you'd access that with [0] to get the string
var temp = ["one, two, three"];
var arr = temp[0].split(", ");
seems easier to just drop the brackets
var arr = "one, two, three".split(', ');
or write it as an array to begin with ?
["one, two, three"].pop().split(", ")
var temp=["one, two, three"];
temp[0].split(", ")