RegEx get value from _GET request - javascript

I'll read more about RegEx in near future, but for now i can't get RegEx for the following:
?filter=aBcD07_1-&developer=true
Need to get only aBcD07_1-, without other.
Can you please help and provide me a RegEx for javascript
Thanks!

A simple substring and indexOf should do the trick.
var startIndex = str.indexOf('filter=') + 7;
str.substring(startIndex, str.indexOf('&', startIndex)); // returns "aBcD07_1"

Try with this one:
var rx = /[?&]filter=([a-zA-Z0-9_-]+).*/g;
var result = rx.exec(yourGetStr);
if (result && result.length == 2) {
alert (result[1]);
}
This regular expression will work even when filter is not the first query parameter.

Related

Javascript Shortcode Parse

I need to parse following shortcode, for example my shortcode is :
[shortcode one=this two=is three=myshortcode]
I want to get this, is and myshortcode and add to array so it will :
['this', 'is', 'myshortcode']
NOTE : I know generally shortcode parameter marked with " and " ( ie [shortcode one="this" two="is" three="myshortcode"] ), but I need to parse shortcode above without ""
Any help really appreciated
I'm assuming you want to parse the first string with Regex and output the three elements in order to add them to an array later. That seems rather simple, or am I misunderstanding what you need? I'm assuming the word shortcodeis as it will be in your string. You'd probably need two regex operations if you haven't located and isolated the shortcode string yet that you posted above:
/\[shortcode((?: \S+=\S+)+)\]/
Replacement: "$1"
If you already have the code exactly as you posted it, then you can skip the regex above. At any rate, you'll have end with the following regex:
/ \S+=(\S+)(?:$| )/g
You can then add all the matches to your array.
If this is is not what you're looking for, then perhaps a more real example of your code would help.
Here you go I have built a perfectly scalable solution for you. The solution works for any number of parameters.
function myFunction() {
var str = "[shortcode one=this two=is three=myshortcode hello=sdfksj]";
var output = new Array();
var res = str.split("=");
for (i = 1; i < res.length; i++) {
var temp = res[i].split(" ");
if(i == res.length-1){
temp[0] = temp[0].substring(0,temp[0].length-1);
}
output.push(temp[0]);
}
document.getElementById("demo").innerHTML = output;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
var str="[shortcode one=this two=is three=myshortcode]";
eval('var obj=' + str.replace(/shortcode /,"").replace(/=/g,"':'").replace(/\[/g,"{'").replace(/\]/g,"'}").replace(/ /g,"','"));
var a=[];
for(x in obj) a.push(obj[x]);
console.log(a);
You can try the above code.
Here's my solution: https://jsfiddle.net/t6rLv74u/
Firstly, remove the [shortcode and trailing ]
Next, split the result by space " "
After that, run through the array and remove anything that's on and before =, .*?=.
And now you have your result.

Failing test as a string

I am running through some exercises and run into this on codewars. Its a simple exercise with Instructions to create a function called shortcut to remove all the lowercase vowels in a given string.
Examples:
shortcut("codewars") // --> cdwrs
shortcut("goodbye") // --> gdby
I am newbie so I thought up this solution. but it doesn't work and I have no idea why
function shortcut(string){
// create an array of individual characters
var stage1 = string.split('');
// loop through array and remove the unneeded characters
for (i = string.length-1; i >= 0; i--) {
if (stage1[i] === "a"||
stage1[i] === "e"||
stage1[i] === "i"||
stage1[i] === "o"||
stage1[i] === "u") {
stage1.splice(i,1)
;}
};
// turn the array back into a string
string = stage1.join('');
return shortcut;
}
My gut is telling me that it will probably something to like split and join not creating "true" array's and strings.
I did it at first with a regex to make it a little more reusable but that was a nightmare. I would be happy to take suggestions on other methods of acheiving the same thing.
You are returning the function itself, instead of returning string
Using regex:
var str = 'codewars';
var regex = /[aeiou]/g;
var result = str.replace(regex, '');
document.write(result);
if interested in Regular Expression ;)
function shortcut(str) {
return str.replace(/[aeiou]/g, "");
}

How to format string to mm/dd/yyyy with regex

I have been struggling with this particular regular expression and was wondering if anyone can help. I have an input field that allows users to enter text and if a user enters 01201990 I have a method that converts it to 01/20/19/90 The problem is I don't want the regular expression to continue after the mm/dd/ my end result would look like this 01/20/1990 Any help would be amazing.
var tmparray = [];
tmparray.push(
tmp.model
// here is where I dont know how to prevent the regex
// from continuing after 01/20/
.match(new RegExp('.{1,2}', 'g'))
.join("/")
);
tmp.model = tmparray;
console.log(tmp.model);
You can use replace() in this case
document.write('19101992'.replace(/(\d{2})(\d{2})(\d{4})/, '$1/$2/$3'))
Your code will be like
var tmparray = [];
tmparray.push(
tmp.model
// here is where I dont know how to prevent the regex
// from continuing after 01/20/
.replace(/(\d{2})(\d{2})(\d{4})/g, '$1/$2/$3')
);
tmp.model = tmparray;
console.log(tmp.model);
why not just match on:
/(\d{2})(\d{2})(\d{4})/
then dd/mm/yyyy is:
$1/$2/$3
(I can't see why you'd match {1,2} since you can't tell the difference between 1/11/1990 and 11/1/1990 and in either case would get 11/11/990...)
Try using String.prototype.slice() , String.prototype.concat()
var str = "01201990" , d = "/"
, res = str.slice(0,2).concat(d + str.slice(2,4)).concat(d + str.slice(4));
console.log(res)
use regex [0-9]{2}(?=(?:[0-9]{4})). for more information please check link https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch06s12.html

How to use string.split( ) for the following string in javascript

I have the following string: (17.591257793993833, 78.88544082641602) in Javascript
How do I use split() for the above string so that I can get the numbers separately.
This is what I have tried (I know its wrong)
var location= "(17.591257793993833, 78.88544082641602)";
var sep= location.split("("" "," "")");
document.getElementById("TextBox1").value= sep[1];
document.getElementById("Textbox2").value=sep[2];
Suggestions please
Use regular expression, something as simple as following would work:
// returns and array with two elements: [17.591257793993833, 78.88544082641602]
"(17.591257793993833, 78.88544082641602)".match(/(\d+\.\d+)/g)
You could user Regular Expression. That would help you a lot. Together with the match function.
A possible Regexp for you might be:
/\d+.\d+/g
For more information you can start with wiki: http://en.wikipedia.org/wiki/Regular_expression
Use the regex [0-9]+\.[0-9]+. You can try the regex here.
In javascript you could do
var str = "(17.591257793993833, 78.88544082641602)";
str.match(/(\d+\.\d+)/g);
Check it.
If you want the values as numbers, i.e. typeof x == "number", you would have to use a regular expression to get the numbers out and then convert those Strings into Numbers, i.e.
var numsStrings = location.match(/(\d+.\d+)/g),
numbers = [],
i, len = numsStrings.length;
for (i = 0; i < len; i++) {
numbers.push(+numsStrings[i]);
}

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

Categories