I have the following string :
DetailsParameters = "Id=1,UserId=1,2,3"
In entity framework stored procedure I am trying to split the above string as :
"Id=1" and "UserId=1,2,3"
Currently, I have the following code which is splitting the above mentioned string at comma which is incorrect.
if (DetailsParameters != "")
{
List<Details> adlist = new List<Details>();
DetailsParameters.Split(',').ToList().ForEach(delegate (string s)
{
adlist.Add(new Details()
{
AlarmLogId = AlarmLogId,
ParameterKey = s.Substring(0, s.IndexOf('=')),
ParameterValue = s.Substring(s.IndexOf('=') + 1, (s.Length - (s.IndexOf('=') + 1)))
});
});
context.Details.AddRange(adlist);
No need to get too complicated about it, you could do something like this:
//var DetailsParameters = "Id=1,UserId=1,2,3";
//var DetailsParameters = "UserId=1,2,3,Id=1";
var indexOf = DetailsParameters.IndexOf("UserId=");
//if the index of "UserId=" is at the start, it should find the other word "Id=" to split
if (indexOf == 0) indexOf = DetailsParameters.IndexOf("Id=", "UserId=".Length);
var firstParameter = DetailsParameters.Substring(0, indexOf);
var secondParameter = DetailsParameters.Substring(indexOf, DetailsParameters.Length - firstParameter.Length);
var firstParameterValue = firstParameter.Split('=')[1].Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries);
var secondParameterValues = secondParameter.Split('=')[1].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
Related
I am sending the arrays from jquery to controller, and this arrays I am getting as String in controller String getIdVal = ParamUtil.getString(resourceRequest, "getId");
The Values in String getIds are like getIdVal ="1_ABC,2_ABC,3_ABC,4_NMO,5_NMO,6_XYZ";
I am trying to get the result but no successes.
(Considering 1 is key ABC is value).
I wanted to remove ABC(ie repeated values) from all keys and append only once at the end. And at the same time I want the keys of repeated values should be like this (1-2-3_ABC). Finally the String should look like this "1-2-3_ABC,4-5_NMO,6_XYZ"
here I am try8ing to split based on comma, but I dont know how to solve.
List<String> keysVals = new ArrayList<String>(Arrays.asList(getIdVal .split(",")));
String getKeyVal;
String[] getKeys;
String key;
String value;
for (String getKeysVals : keysVals) {
getKeyVal = getKeysVals;
getKeys = getKeyVal.split("\\_");
key = getKeys[0];
value = getKeyVal.substring(getKeyVal.lastIndexOf("_") + 1) .trim();
// i am not getting how to check for dublicate
}
Did you mean something like this?
private static String mergeKeys(String input) {
Map<String, StringBuilder> valKeys = new TreeMap<>();
if (! input.isEmpty())
for (String keyVal : input.split(",")) {
int idx = keyVal.indexOf('_');
String key = keyVal.substring(0, idx);
String val = keyVal.substring(idx + 1);
StringBuilder builder = valKeys.get(val);
if (builder == null)
valKeys.put(val, new StringBuilder(key));
else
builder.append('-').append(key);
}
StringJoiner result = new StringJoiner(",");
for (Entry<String, StringBuilder> entry : valKeys.entrySet())
result.add(entry.getValue().append('_').append(entry.getKey()).toString());
return result.toString();
}
Or this slow version of the same logic, using string = string + string (Yikes!):
private static String mergeKeys(String input) {
Map<String, String> valKeys = new LinkedHashMap<>();
if (! input.isEmpty())
for (String keyVal : input.split(",")) {
int idx = keyVal.indexOf('_');
String key = keyVal.substring(0, idx);
String val = keyVal.substring(idx + 1);
String prevKeys = valKeys.get(val);
valKeys.put(val, prevKeys == null ? key : prevKeys + "-" + key);
}
String result = "";
for (Entry<String, String> entry : valKeys.entrySet())
result += "," + entry.getValue() + "_" + entry.getKey();
return result.substring(1); // skip leading comma
}
TEST
System.out.println(mergeKeys("1_ABC,2_ABC,3_ABC,4_NMO,5_NMO,6_XYZ"));
OUTPUT
1-2-3_ABC,4-5_NMO,6_XYZ
In the below code Im not getting the right result. How can I can do pattern match in javascript?
function getPathValue(url, input) {
console.log("this is path key :"+input);
url = url.replace(/%7C/g, '|');
var inputarr = input.split("|");
if (inputarr.length > 1)
input = '\\b' + inputarr[0] + '\n|' + inputarr[1] + '\\b';
else
input = '\\b' + input + '\\b';
var field = url.search(input);
var slash1 = url.indexOf("/", field);
var slash2 = url.indexOf("/", slash1 + 1);
if (slash2 == -1)
slash2 = url.indexOf("?");
if (slash2 == -1)
slash2 = url.length;
console.log("this is path param value :"+url.substring(slash1 + 1, slash2));
return url.substring(slash1 + 1, slash2);
}
getPathValue("http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1","mountainwithpassid|passid")
Im getting the below output
If I pass mountainwithpassid|accesscode as input Im getting output as
100. Same way if I pass
key :mountainwithpassid|passid value :100 // Expected output 1
If your intention is to simply retrieve the value in the path that follows the input (contained within '/') then you can achieve this with a simpler regular expression. First you will need a method to escape your input string since it contains a pipe character '|' which is translated as OR in regex.
You can use this (taken from https://stackoverflow.com/a/3561711):
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
Then your getPathValue function can look something like:
function getPathValue(url, input) {
var pathValue = null;
var escapedInput = RegExp.escape(input);
// The RegExp below extracts the value that follows the input and
// is contained within '/' characters (the last '/' is optional)
var pathValueRegExp = new RegExp(".*" + escapedInput + "/([^/]+)/?.*", 'g');
if (pathValueRegExp.test(url)) {
pathValue = url.replace(pathValueRegExp, '$1');
}
return pathValue;
}
You will also need to think about how you handle errors - in the example a null value is returned if no match is found.
I'm trying to understand the question. Given a URL of:
"http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1"
and an argument of:
"mountainwithpassid|passid"
you expect a return value of:
"1"
An argument of
"mountainwithpassid|accesscode"
should return:
"100"
Is that correct? If so (and I'm not certain it is) then the following may suit:
function getPathValue(url, s) {
var x = url.indexOf(s);
if (x != -1) {
return url.substr(x).split('/')[1];
}
}
var url = "http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1";
var x = "mountainwithpassid|passid";
var y = "mountainwithpassid|accesscode";
console.log(getPathValue(url, x)); // 1
console.log(getPathValue(url, y)); // 100
My problem is I am trying to extract certain things from the url. I am currently using
window.location.href.substr()
to grab something like "/localhost:123/list/chart=2/view=1"
What i have now, is using the index positioning to grab the chart and view value.
var chart = window.location.href.substr(-8);
var view = window.location.href.substr(-1);
But the problem comes in with I have 10 or more charts. The positioning is messed up. Is there a way where you can ask the code to get the string between "chart=" and the closest "/"?
var str = "/localhost:123/list/chart=2/view=1";
var data = str.match(/\/chart=([0-9]+)\/view=([0-9]+)/);
var chart = data[1];
var view = data[2];
Of course you may want to add in some validation checks before using the outcome of the match.
Inspired by Paul S. I have written a function version of my answer:
function getPathVal(name)
{
var path = window.location.pathname;
var regx = new RegExp('(?:/|&|\\?)'+name+'='+'([^/&,]+)');
var data = path.match(regx);
return data[1] || null;
}
getPathVal('chart');//2
Function should work for fetching params from standard get parameter syntax in a URI, or the syntax in your example URI
Here's a way using String.prototype.indexOf
function getPathVar(key) {
var str = window.location.pathname,
i = str.indexOf('/' + key + '=') + key.length + 2,
j = str.indexOf('/', i);
if (i === key.length + 1) return '';
return str.slice(i, j);
}
// assuming current path as described in question
getPathVar('chart');
You could split your string up, with "/" as delimiter and then loop through the resulting array to find the desired parameters. That way you can easily extract all parameters automatically:
var x = "/localhost:123/list/chart=2/view=1";
var res = {};
var spl = x.split("/");
for (var i = 0; i < spl.length; i++) {
var part = spl[i];
var index = part.indexOf("=");
if (index > 0) {
res[part.substring(0, index)] = part.substring(index + 1);
}
}
console.log(res);
// res = { chart: 2, view: 1}
FIDDLE
I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}
I cannot find out the regex to get param value from the part of query string:
I need to send parameter name to a method and get parameter value as result for string like
"p=1&qp=10".
I came up with the following:
function getParamValue(name) {
var regex_str = "[&]" + name + "=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
// check if result found and return results[1]
}
My regex_str now doesn't work if name = 'p'. if I change regex_str to
var regex_str = name + "=([^&]*)";
it can return value of param 'qp' for param name = 'p'
Can you help me with regex to search the beginning of param name from right after '&' OR from the beginning of a string?
This might work, depending on if you have separated the parameter part.
var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";
Looks like split will work better here:
var paramsMap = {};
var params = string.split("&");
for (var i = 0; i < params.length; ++i) {
var keyValue = params[i].split("=", 2);
paramsMap[keyValue[0]] = keyValue[1];
}
If you desperately want to use a regex, you need to use the g flag and the exec method. Something along the lines of
var regex = /([^=]+)=([^&]+)&?/g;
var paramsMap = {};
while (true) {
var match = regex.exec(input);
if (!match)
break;
paramsMap[match[1]] = match[2];
}
Please note that since the regex object becomes stateful, you either need to reset its lastIndex property before running another extraction loop or use a new RegExp instance.
Change your regex string to the following:
//pass the query string and the name of the parameter's value you want to retrieve
function getParamValue(my_query_string , name)
{
var regex_str = "(?:^|\&)" + name + "\=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
try
{
if(results[1] != '')
{
return results[1];
}
}
catch(err){};
return false;
}