Hey everyone quick question, I know this sounds strange to do in javascript but i have good use for it. I need to be able to parse a string passed in a textarea in such a way that escaped hex literals "\x41" or whatever are processed not as four chars '\' 'x' '4' '1' but as 'A' for example:
var anA = "\x41";
console.log(anA); //emits "A"
var stringToParse = $(#someTextArea).val(); //using jquery for ease not a req
//lets say that "someTextArea" contains "\x41"
console.log(stringToParse); // equals "\" "x" "4" "1" -- not what i want
console.log(new String(stringToParse)); same as last
console.log(""+stringToParse); still doesnt work
console.log(stringToParse.toString()); failz all over (same result)
I want to be able to have a way for stringToParse to contain "A" not "\x41"... any ideas beyond regex? I'll take a regex i guess, i just wanted a way to make javascript do my bidding :)
String.prototype.parseHex = function(){
return this.replace(/\\x([a-fA-F0-9]{2})/g, function(a,b){
return String.fromCharCode(parseInt(b,16));
});
};
and in practice:
var v = $('#foo').val();
console.log(v);
console.log(v.parseHex());
I figured it out although its kind of hacky and i use eval :(... if anyone has a better way let me know:
stringToParse = stringToParse.toSource().replace("\\x", "\x");
stringToParse = eval(stringToParse);
console.log(stringToParse);
mainly i needed this to parse mixed strings... as in string literals with hex mixed in
Related
I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.
I am trying to get the values from a string using regex, the value is that of the text between tt=" and "&
So, for example, "tt="Value"&" I would only want to get the word "Value" out of this.
So far I have this: /tt=.*&/ which gives me "tt=Value"&, Then, to get the value I am thinking to split the match on = and remove the 2 characters from the end. I feel though, that this would be an awful way to do this and would like to see if it could be done in the regex?
You're on the right track for matching the entire context inside of the string, but you want to use a capturing group to match/capture the value between the quotes instead of splitting on = and having to remove the two quote chars.
var r = 'tt="Value"&'.match(/tt="([^"]*)"/)[1];
if (r)
console.log(r); //=> "Value"
I know this isn't really the answer you are looking for since it doesn't involve regex but it's the way I usually do it.
strvariable = strvariable.Remove(0,strvariable.IndexOf("=") + 2);
strvariable = strvariable.Remove(strvariable.IndexOf("\""), strvariable.Length - strvariable.IndexOf("\""));
this would give you the result you were looking for which is Value in this instance.
Give the following string:
http://foobar.com/trusted/123/views/AnalyticsInc
..where 123 will be a number anywhere between 0 and 9999999, I need to be able to dynamically replace said value with a different value
I assume the best way to approach this is to do a string.replace with some sort of regex pattern, since we can count on the fact that "/trusted/" and "/views/" will always surround the value that needs to be swapped out.
var foo='http://foobar.com/trusted/123/views/AnalyticsInc';
var newvalue=654321;
magic(); //magic happens here
console.log(foo); //returns http://foobar.com/trusted/654321/views/...etc
But my regex kung-fu is so weak I cannot defeat a kitten. Can someone give me a hand? Or if there's a better approach, I'd love to learn it. Thanks!
It will replace the first occurrence of number from 0 to 9999999 in foo string:
foo = foo.replace(/\d{1,7}/, newvalue);
DEMO: http://jsfiddle.net/D4teZ/
#&q=car&category=Car%20Audio%2CAccessories&brand=
I borrowed a this function from a previous question asked on SO:
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.hash.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.hash = kvp.join('&');
}
I use it like this:
insertParam("category",xy);
insertParam("brand",zy);
My problem is it is decoding comma's to %2C. I know I can handle the characters on the server side, but how can I make it look pretty with javascript? By pretty I mean replace %2c with a comma.
I do not know why in the previous answer that was striked out, but the answer was correct.
alert(decodeURIComponent('%2C'));
So, you break your query strings into elements, splitting by & symbol. Than you split the results by = symbol and apply decodeURIComponent on both name and the value.
ps: key = escape(key); value = escape(value); you should not use escape here (it is different for different browsers. and by 'different' I meant IE). Use encodeURIComponent.
pps: because they either encode commas or don't encode &=???
alert(encodeURIComponent('&=,'));
outputs %26%3D%2C
This worked for me for undoing encodeURIComponent() on URIs that contain commas:
.replace(/%2C/g,",")
decodeURIComponent(foo) is the thing you are looking for.
Edit: Misread your question.
Use replace(/&/g, "%26").replace(/=/g, "%3D") instead of escape on key and value to do this.
None of the 3 functions encodeURI, encodeURIComponent or encode work for this task, because they either encode commas or don't encode &=.
How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.