JavaScript RegExp - find all prefixes up to a certain character - javascript

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);

Related

How to split string with multiple semi colons javascript

I have a string like below
var exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
I want to split above string with semi colon, so want the array like
var result = [ "Name:Sivakumar ; Tadisetti", "Country:India" ]
But as the name contains another semi colon, I am getting array like
var result = [ "Name:Sivakumar ", "Tadisetti", "Country:India" ]
Here Sivakumar ; Tadisetti value of the key Name
I just wrote the code like exampleString.split(';')... other than this not able to get an idea to proceed further to get my desired output. Any suggestions?
Logic to split: I want to split the string as array with key:value pairs
Since .split accepts regular expressions as well, you can use a one that matches semicolons that are only followed by alphanumeric characters that end in : (in effect if they are followed by another key)
/;(?=\w+:)/
var exampleString = "Name:Sivakumar ; Tadisetti;Country:India";
var result = exampleString.split(/;(?=\w+:)/);
console.log(result)
here is an approach which we first split the input on ; and then concat the element without : with the previous one; since it shouldn't being spited.
let exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
let reverseSplited = exampleString.split(";").reverse();
let prevoiusString;
let regex = /[^:]+:.*/;
let result = reverseSplited.map( str => {
if(regex.test(str)) {
if(prevoiusString){
let returnValue = str + ";" + prevoiusString;
prevoiusString = null;
return returnValue
}
return str
}
prevoiusString = str;
}).filter(e=>e);
console.log(result);

JavaScript Split with RegEx without Global Match

I have an expression.
var expression = "Q101='You will have an answer here like a string for instance.'"
I have a regular expression that searches the expression.
var regEx = new regExp(/=|<>|like/)
I want to split the expression using the regular expression.
var result = expression.split(regExp)
This will return the following:
["Q101", "'You will have an answer here ", " a string for instance'"]
This is not what I want.
I should have:
["Q101", "'You will have an answer here like a string for instance'"]
How do I use the regular expression above to split only on the first match?
Since you only want to grab the two parts either side of the first delimiter it might be easier to use String.match and discard the whole match:
var expression = "Q101='You will have an answer here like a string for instance.'";
var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
JavaScript's split method won't quite do what you want, because it will either split on all matches, or stop after N matches. You need an extra step to find the first match, then split once by the first match using a custom function:
function splitMatch(string, match) {
var splitString = match[0];
var result = [
expression.slice(0, match.index),
expression.slice(match.index + splitString.length)
];
return result;
}
var expression = "Q101='You will have an answer here like a string for instance.'"
var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)
if (match) {
var result = splitMatch(expression, match);
console.log(result);
}
While JavaScript's split method does have an optional limit parameter, it simply discards the parts of the result that make it too long (unlike, e.g. Python's split). To do this in JS, you'll need to split it manually, considering the length of the match —
const exp = "Q101='You will have an answer here like a string for instance.'"
const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]
const result = splitPos != -1 ? (
[
exp.substring(0, splitPos),
exp.substring(splitPos + splitStr.length),
]
) : (
null
);
console.log(result)

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 split only once and ignore the rest

I am parsing some key value pairs that are separated by colons. The problem I am having is that in the value section there are colons that I want to ignore but the split function is picking them up anyway.
sample:
Name: my name
description: this string is not escaped: i hate these colons
date: a date
On the individual lines I tried this line.split(/:/, 1) but it only matched the value part of the data. Next I tried line.split(/:/, 2) but that gave me ['description', 'this string is not escaped'] and I need the whole string.
Thanks for the help!
a = line.split(/:/);
key = a.shift();
val = a.join(':');
Use the greedy operator (?) to only split the first instance.
line.split(/: (.+)?/, 2);
If you prefer an alternative to regexp consider this:
var split = line.split(':');
var key = split[0];
var val = split.slice(1).join(":");
Reference: split, slice, join.
Slightly more elegant:
a = line.match(/(.*?):(.*)/);
key = a[1];
val = a[2];
May be this approach will be the best for such purpose:
var a = line.match(/([^:\s]+)\s*:\s*(.*)/);
var key = a[1];
var val = a[2];
So, you can use tabulations in your config/data files of such structure and also not worry about spaces before or after your name-value delimiter ':'.
Or you can use primitive and fast string functions indexOf and substr to reach your goal in, I think, the fastest way (by CPU and RAM)
for ( ... line ... ) {
var delimPos = line.indexOf(':');
if (delimPos <= 0) {
continue; // Something wrong with this "line"
}
var key = line.substr(0, delimPos).trim();
var val = line.substr(delimPos + 1).trim();
// Do all you need with this key: val
}
Split string in two at first occurrence
To split a string with multiple i.e. columns : only at the first column occurrence
use Positive Lookbehind (?<=)
const a = "Description: this: is: nice";
const b = "Name: My Name";
console.log(a.split(/(?<=^[^:]*):/)); // ["Description", " this: is: nice"]
console.log(b.split(/(?<=^[^:]*):/)); // ["Name", " My Name"]
it basically consumes from Start of string ^ everything that is not a column [^:] zero or more times *. Once the positive lookbehind is done, finally matches the column :.
If you additionally want to remove one or more whitespaces following the column,
use /(?<=^[^:]*): */
Explanation on Regex101.com
function splitOnce(str, sep) {
const idx = str.indexOf(sep);
return [str.slice(0, idx), str.slice(idx+1)];
}
splitOnce("description: this string is not escaped: i hate these colons", ":")

Categories

Resources