How to split string with multiple semi colons javascript - 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);

Related

Javascript split by numbers using regex

I'm trying to come up with a regex that will do following.
I have a string
var input_string = "E100T10P200E3000T3S10";
var output=input_string.split(**Trying to find this**);
this should give an array with all the letters in order with repetitions
output = ["E","T","P","E","T","S"]
See below. \d+ means one or more digits; filter (x => x) removes empty strings that can appear in the beginning or the end of the array if the input string begins or ends with digits.
var input_string = "E100T10P200E3000T3S10";
var output = input_string.split (/\d+/).filter (x => x);
console.log (output);
We can try just matching for capital letters here:
var input_string = "E100T10P200E3000T3S10";
var output = input_string.match(/[A-Z]/g);
console.log(output);
Another approach is spread the string to array and use isNaN as filter callback
var input_string = "E100T10P200E3000T3S10";
var output = [...input_string].filter(isNaN);
console.log(output);
You can use regex replace method. First replace all the digits with empty string and then split the resultant string.
const input_string = 'E100T10P200E3000T3S10';
const ret = input_string.replace(/\d/g, '').split('');
console.log(ret);

How Can I convert this complex a string into JSON with "" in key values?

I am trying to convert a string to json.
var str = "[{Value:0.64,Rate:Hourly,Description:Hourly if more than 50 hours,Upper Limit:null},{Value:1.68,Rate:Hourly,Description:Hourly if less than 400 hours,Upper Limit:500}]"
I tried with stringify and parse but that didn't work.
I tried with below function :
function getJsonData(query){
let arrayOfKeyValues = query.split(',');
let modifiedArray = new Array();
console.log(arrayOfKeyValues);
for(let i=0;i< arrayOfKeyValues.length;i++){
let arrayValues = arrayOfKeyValues[i].split(':');
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
modifiedArray.push(arrayString);
}
let jsonDataString = '{'+modifiedArray.toString()+'}';
let jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
console.log(typeof jsonData);
return jsonData;
}
Is there a way to use regex or this function to get the expected output with double quotes ("") added
to each key value?
I have to as least make the assumption that your KEYS all do not contain a comma.
Because, say you have:
{a:b,c,d:e}
It is ambiguous whether it should be: {a:"b","c,d":"e"} or {a:"b,c",d:"e"}
Just for simplicity, I am also assuming there is no {, }, : characters in your key or value...
The expression is:
JSON.parse(
str
.replace(new RegExp('{','g'),'{"')
.replace(new RegExp('}','g'),'"}')
.replace(new RegExp(':','g'),'":"')
.replace(new RegExp(',([^{][^,]*:)','g'),'","$1')
)
This will be the outcome:
var str = "[{Value:0.64,Rate:Hourly,Description:Hourly if more than 50 hours,Upper Limit:null},{Value:1.68,Rate:Hourly,Description:Hourly if less than 400 hours,Upper Limit:500}]"
const regStr = str
.replace(/:/g,'":"')
.replace(/,/g,'","')
.replace(/}","{/g,'"},{"')
.replace(/^\[{/,'[{"')
.replace(/}]$/, '"}]')
jsonResult = JSON.parse(regStr)
console.log(jsonResult);

Finding white space in string and replace that with another in an array

I have a set of strings in array like ['1254','1556',' 515']. From here I want to look for a string which has a white space and three digits. Also I want to replace that string with ----. How can I do that as the strings are in an array?
You could take a regular expression for testing the string and replace the value for a new array.
var array = ['1254','1556',' 515'],
result = array.map(s => /^\s\d{3}$/.test(s) ? '----' : s);
console.log(result);
You can use
^(?=.* )(?=.*\d{3})[\d\s]+$
let arr = ['1254','1556',' 515']
let replaceStr = (str) => {
return str.replace(/^(?=.* )(?=.*\d{3})[\d\s]+$/,(match)=> '-'.repeat(match.length))
}
let final = arr.map(replaceStr)
console.log(final)

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

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

Categories

Resources