Get String Specific Characters - javascript

I am trying to write some code that takes a uuid string and returns only the characters between the 2nd and 3rd _ characters in an array. What I currently have below is returning every character in the string in to the array. I have been looking at this for some time and am obviously missing something glaringly obvious I suppose. Can someone maybe point out what is wrong here?
var uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
var count = 0
var values = []
for(y=0; y<uuid.length; y++){
if(uuid.charAt(y) == '_'){
count++
}
if(count = 2){
values.push(uuid.charAt(y))
}
}
return values
EDIT:
So for my case I would want the values array to contain all of the characters in 5be0lk875iou

You can get the same behavior in less lines of code, like this:
let uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
let values = uuid.split("_")[2];

You can use the split function to do that:
let values = uuid.split("_");

By using the split function, you can get separate the whole string into smaller parts:
const parts = uuid.split("_");
This will return the following array:
["159as", "ss", "5be0lk875iou", ".1345.332.11.2"]
From here, you can take the string at index 2, and split it again to receive an array of characters:
const values = parts[2].split("");

Related

make array from string by converting datatype using javascript

The string I have is as like as follows
let a = "0j (0.001953125+0j) (-0.001953125+0.001953125j) (0.998046875+0j) (-0.001953125+0j) (0.001953125+0j) (0+0.0914587j)"
Info about the string:
1/ Each substring is complex number in the format of a+bj
2/ Possible format of the complex number could be a+bj,a,bj. Eg: 1+2j, 1,2j
3/ There is a space( ) between each substring
4/ I have seen that 0+bj(eg: 0+5j) or a+0j(eg: 5+0j) format is not possible/ created by the backend so this type of format/ presentation is not considered for my case.
5/ If the substring contains only real/imaginary part then parenthesis () will not be used. Eg: (5),(5j) is not possible. They will be 5,5j
I need to create a JSON or JavaScript object from that string which will be used to plot data. The data is coming from the Flask backend and it is different for each request. One approach I have found to make this JSON object is from an array which should look like
let my_array = [[0,0], [0.001953125,0], [-0.001953125,0.001953125], [0.998046875,0],[-0.001953125,0],[-0.001953125,0],[0,0.914587]]
But I am totally lost in making of this array. Initially, I have removed all the j from the string by a.replaceAll("j","") but then I have not found a way to make my desired array structure. If I get the array, I can make the JSON object with the following approach:
my_array = [[0,0], [0.001953125,0], [-0.001953125,0.001953125], [0.998046875,0],[-0.001953125,0],[-0.001953125,0],[0,0.914587]]
temp_key = ["i", "q"]
my_json = {
}
for(let a = 0; a < my_array.length; a++){
temp_json = {};
for(let b = 0; b < my_array[a].length; b++){
temp_json[temp_key[b]] = my_array[a][b];
}
my_json[String(a)] = temp_json;
}
console.log("my_json: ",my_json)
Suggestions regarding making this array will be appreciated.
You can split by whitespace, then use a regular expression to match digit characters in the substring (eg 0.001953125+0j to 0.001953125 and 0).
const str = "0j (0.001953125+0j) (-0.001953125+0.001953125j) (0.998046875+0j) (-0.001953125+0j) (0.001953125+0j) (0+0.914587j)";
const arr = str
.split(' ')
.map((substr) => {
const [real, imag = 0] = substr.match(/-?\d+(?:\.\d+)?/g).map(Number);
return [real, imag];
});
console.log(arr);
-?\d+(?:\.\d+)? is:
-? - possibly match a leading -
\d+ - match one or more digits
(?:\.\d+)? - optionally match the following (the decimal part of a number):
\. - a literal .
\d+ - one or more digits

Parse strings with a regex and store the result in an array or a string

I need some help to improve my code :
I am beginner with regex system.
I would like to fecth NUMBER below in script and store it in a string or an array to moment that output "NUMBER1,NUMBER1_NUMBER2_,NUMBER2" I don't understand why, i would like jsut NUMBER at the end ;
function fetchnumber(){
extract = "";
for(picture = 1 ; picture < 5; picture++){
// get background image as a string as this :
// url('http://www.mywebsite.com/directory/image_NUMBER_.png');
var NumberOfPicture = document.getElementById(picture).style.backgroundImage ;
reg = /\_(.*)\_/;
extract += reg.exec(NumberOfPicture);
}
}
I write this small example for you. Hope this help you.
var inputString = 'http://www.mywebsite.com/directory/image_123_.png';
var imageNumber = (/image_([^_]+)_\.\w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
// here you can do something with finded
// part of text.
}
I wish you luck with the implementation.
You asked why there is [1] instead [0]. The explanation is that we need to have
the same behavior when there is no match of regex. This is quote from MDN
The exec() method executes a search for a match in a specified string.
Returns a result array, or null.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
So. If there is match for regular expression the returned array will consist
from matched string located at zero index ([0]) and with first backreference at first index [1] back references are symbols between brackets (sddsd). But if there is no match we will pass [,false] as output so we will expect the result
into first array index [1]. Try the code with different input. For example:
var inputString = 'some text some text ';
var imageNumber = (/image_([^_]+)_\.\w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
// here you can do something with finded
// part of text.
}
So .. In this case the condition will not be executed at all. I mean:
if (imageNumber) {
// here you can do something with finded
// part of text.
}

How to split a string by Node Js?

My array:
var str=['data1,data2 '];
I have used:
var arr = str.split(",");
But one error is showed. TypeError: Object data1,data2 has no method 'split'. How can I solve this problem.
My output will be:
arr= data1,data2
// or
arr[0]=data1;
arr[1]=data2;
How can I solve this problem ?
You should do this :
var arr = str.toString().split(",");
"TypeError: Object data1,data2 has no method 'split'" indicates the variable is not considered as a string. Therefore, you must typecast it.
update 08.10.2015 I have noticed someone think the above answer is a "dirty workaround" and surprisingly this comment is upvoted. In fact it is the exact opposite - using str[0].split(",") as 3 (!) other suggests is the real "dirty workaround". Why? Consider what would happen in these cases :
var str = [];
var str = ['data1,data2','data3,data4'];
var str = [someVariable];
str[0].split(",") will fail utterly as soon str holds an empty array, for some reason not is holding a String.prototype or will give an unsatisfactory result if str holds more than one string. Using str[0].split(",") blindly trusting that str always will hold 1 string exactly and never something else is bad practice. toString() is supported by numbers, arrays, objects, booleans, dates and even functions; str[0].split() has a huge potential of raising errors and stop further execution in the scope, and by that crashing the entire application.
If you really, really want to use str[0].split() then at least do some minimal type checking :
var arr;
if (typeof str[0] == 'string') {
arr = str[0].split(',')
} else {
arr = [];
}
If your starting point is a array with a string inside. This should work:
var arr = str[0].split(",");
Otherwise you should have a string as starting point for your code to work as you expected:
var str = 'data1,data2';
If you have more elements in the array you will need to iterate them with a for loop.
Edit to add other cases:
If you have several strings in that array, then you should be more carefull and do something like this:
var str = ['data1,data2 ', ' data3, data4 ']; // notice these strings have many spaces in different places
var longString = str.join(',');
var array = longString.split(',').map(s => s.trim()).filter(Boolean); // removing spaces from start and end of strings, and eventually removing empty positions
console.log(array);
As you said, str is an array (with one element). If you want to split the string contained in the array, you have to access the array first:
var arr = str[0].split(",");
let's say we have two date :
date1: 17/01/1989
date2: 20/02/2000
if we want to compare them just split the string and compare like this
var date1= date1.toString().split("/");
var date2= date2.toString().split("/");
var a = parseInt(date1[2] + date1[1] + date1[0]);
var b = parseInt(date2[2] + date2[1] + date2[0]);
if(a < b){
alert("date2 bigger than date1")}
}
else if(a > b){
alert("date1 bigger than date2")
}
else{
alert("date 1 and date2 are equals ");
}

Regular expression in Javascript: table of positions instead of table of occurrences

Regular expressions are most powerful. However, the result they return is sometimes useless:
For example:
I want to manage a CSV string using semicolons.
I define a string like:
var data = "John;Paul;Pete;Stuart;George";
If I use the instruction:
var tab = data.match(/;/g)
after what, "tab" contains an array of 4 ";" :
tab[0]=";", tab[1]=";", tab[2]=";", tab[3]=";"
This array is not useful in the present case, because I knew it even before using the regular expression.
Indeed, what I want to do is 2 things:
1stly: Suppress the 4th element (not "Stuart" as "Stuart", but "Stuart" as 4th element)
2ndly: Replace the 3rd element by "Ringo" so as to get back (to where you once belonged!) the following result:
data == "John;Paul;Ringo;George";
In this case, I would greatly prefer to obtain an array giving the positions of semicolons:
tab[0]=4, tab[1]=9, tab[2]=14 tab[3]=21
instead of the useless (in this specific case)
tab[0]=";", tab[1]=";", tab[2]=";", tab[3]=";"
So, here's my question: Is there a way to obtain this numeric array using regular expressions?
To get tab[0]=4, tab[1]=9, tab[2]=14 tab[3]=21, you can do
var tab = [];
var startPos = 0;
var data = "John;Paul;Pete;Stuart;George";
while (true) {
var currentIndex = data.indexOf(";", startPos);
if (currentIndex == -1) {
break;
}
tab.push(currentIndex);
startPos = currentIndex;
}
But if the result wanted is "John;Paul;Ringo;George", you can do
var tab = data.split(';'); // Split the string into an array of strings
tab.splice(3, 1); // Suppress the 4th element
tab[2] = "Ringo"; // Replace the 3rd element by "Ringo"
var str = tab.join(';'); // Join the elements of the array into a string
The second approach is maybe better in your case.
String.split
Array.splice
Array.join
You should try a different approach, using split.
tab = data.split(';') will return an array of the form
tab[0]="John", tab[1]="Paul", tab[2]="Pete", tab[3]="Stuart", tab[4]="George"
You should be able to achieve your goal with this array.
Why use a regex to perform this operation? You have a built-in function split, which can split your string based on the delimiter you pass.
var data = "John;Paul;Pete;Stuart;George";
var temp=data.split(';');
temp[0],temp[1]...

How to remove the last matched regex pattern in javascript

I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.

Categories

Resources