Split the date! (It's a string actually) - javascript

I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help

You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");

If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>

Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.

var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");

.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]

Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

Related

replace a string partially with something else

lets say I have this image address like
https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
how is it possible to replace FILE_NAME.jpg with THUMB_FILE_NAME.jpg
Note: FILE_NAME and THUMB_FILE_NAME are not static and fix.
the FILE_NAME is not fixed and I can't use string.replace method.
eventually I don't know the File_Name
Use replace
.replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME")
or if you want to support multiple formats
.replace(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g, "THUMB_FILE_NAME")
Demo
var output = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b".replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME");
console.log( output );
Explanation
(?<=\/) matches / but doesn't remember the match
[^\/]* matches till you find next /
(?=(.jpg) ensures that match ends with .jpg
To match the FILE_NAME, use
.match(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g)
var pattern = /[\w-]+\.(jpg|png|txt)/
var c = 'https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
'
c.replace(pattern, 'YOUR_FILE_NAME.jpg')
you can add any format in the pipe operator
You can use the String's replace method.
var a = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
a = a.replace('FILE_NAME', 'THUMB_FILE_NAME');
If you know the format, you can use the split and join to replace the FILE_NAME.
let str = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
let str_pieces = str.split('/');
let str_last = str_pieces[str_pieces.length - 1];
let str_last_pieces = str_last.split('?');
str_last_pieces[0] = 'THUMB_' + str_last_pieces[0];
str_last = str_last_pieces.join('?');
str_pieces[str_pieces.length - 1] = str_last;
str = str_pieces.join('/');

JavaScript RegExp - find all prefixes up to a certain character

I have a string which is composed of terms separated by slashes ('/'), for example:
ab/c/def
I want to find all the prefixes of this string up to an occurrence of a slash or end of string, i.e. for the above example I expect to get:
ab
ab/c
ab/c/def
I've tried a regex like this: /^(.*)[\/$]/, but it returns a single match - ab/c/ with the parenthesized result ab/c, accordingly.
EDIT :
I know this can be done quite easily using split, I am looking specifically for a solution using RegExp.
NO, you can't do that with a pure regex.
Why? Because you need substrings starting at one and the same location in the string, while regex matches non-overlapping chunks of text and then advances its index to search for another match.
OK, what about capturing groups? They are only helpful if you know how many /-separated chunks you have in the input string. You could then use
var s = 'ab/c/def'; // There are exact 3 parts
console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s));
// => [ "ab/c/def", "ab/c", "ab" ]
However, it is unlikely you know that many details about your input string.
You may use the following code rather than a regex:
var s = 'ab/c/def';
var chunks = s.split('/');
var res = [];
for(var i=0;i<chunks.length;i++) {
res.length > 0 ? res.push(chunks.slice(0,i).join('/')+'/'+chunks[i]) : res.push(chunks[i]);
}
console.log(res);
First, you can split the string with /. Then, iterate through the elements and build the res array.
I do not think a regular expression is what you are after. A simple split and loop over the array can give you the result.
var str = "ab/c/def";
var result = str.split("/").reduce(function(a,s,i){
var last = a[i-1] ? a[i-1] + "/" : "";
a.push(last + s);
return a;
}, []);
console.log(result);
or another way
var str = "ab/c/def",
result = [],
parts=str.split("/");
while(parts.length){
console.log(parts);
result.unshift(parts.join("/"));
parts.pop();
}
console.log(result);
Plenty of other ways to do it.
You can't do it with a RegEx in javascript but you can split parts and join them respectively together:
var array = "ab/c/def".split('/'), newArray = [], key = 0;
while (value = array[key++]) {
newArray.push(key == 1 ? value : newArray[newArray.length - 1] + "/" + value)
}
console.log(newArray);
May be like this
var str = "ab/c/def",
result = str.match(/.+?(?=\/|$)/g)
.map((e,i,a) => a[i-1] ? a[i] = a[i-1] + e : e);
console.log(result);
Couldn't you just split the string on the separator character?
var result = 'ab/c/def'.split(/\//g);

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

javascript - get two numbers from a string

I have a string like:
text-345-3535
The numbers can change.
How can I get the two numbers from it and store that into two variables?
var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"
If you're not accustomed to regular expressions, #patrick dw's answer is probably better for you, but this should work as well:
var strSource = "text-123-4567";
var rxNumbers = /\b(\d{3})-(\d{4})\b/
var arrMatches = rxNumbers.exec(strSource);
var strFirstCluster, strSecondCluster;
if (arrMatches) {
strFirstCluster = arrMatches[1];
strSecondCluster = arrMatches[2];
}
This will extract the numbers if it is exactly three digits followed by a dash followed by four digits. The expression can be modified in many ways to retrieve exactly the string you are after.
Try this,
var text = "text-123-4567";
if(text.match(/-([0-9]+)-([0-9]+)/)) {
var x = Text.match(/([0-9]+)-([0-9]+)/);
alert(x[0]);
alert(x[1]);
alert(x[2]);
}
Thanks.
Another way to do this (using String tokenizer).
int idx=0; int tokenCount;
String words[]=new String [500];
String message="text-345-3535";
StringTokenizer st=new StringTokenizer(message,"-");
tokenCount=st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
{words[idx]=st.nextToken(); idx++;}
for (idx=0;idx<tokenCount; idx++)
{System.out.println(words[idx]);}
}
output
words[0] =>text
words[1] => 345
words[2] => 3535

Categories

Resources