I have a string:
for (;;); {
"__ar": 1,
"payload": null,
"jsmods": {
"require": [
["ServerRedirect", "redirectPageTo", [],
["https:\/\/bigzipfiles.facebook.com\/p\/dl\/download\/file.php?r=100028316830939&t=100028316830939&j=11&i=5823694&ext=12121516&hash=AaBVNURld6wrKBcU", true, false]
]
],
"define": [
["KSConfig", []
}
I try to regex this to be:
https://bigzipfiles.facebook.com/p/dl/download/file.php?r=100028316830939&t=100028316830939&j=11&i=5823694&ext=12121516&hash=AaBVNURld6wrKBcU
I've used
var results = $(document).find("pre").html();
var regex1 = new RegExp(/["\w\.\/\;\?\=\-\&\\\\"]/);
var resultsReplace = regex1.exec(results);
console.log(resultsReplace);
but it is not working.
Can anyone help me, please?
Assuming it is always URL and the delimiter is always " we can use a much simpler regex here, like:
str.match(/http[^"]+/)[0]
So we looking for a string starting with http with any following characters except " since the match string never can get one because this is a delimiter.
LMK if cases are wider (not an url, may not start with http, etc.) and I'll adjust regex.
Related
Im trying to remove the space after and before closing parenthesis using regex, the problem is that Safari not supporting my solution, is there any alternative for using "lookbehind" functionality?
My string for example:
check IN [ "[hello world]*" ] OR host IN ( abc,123)
Im expecting to get:
check IN ["[hello world]*"] OR host IN (abc,123)
My current solution:
(?<=[([])\s+|\s+(?=[)\]])
Assuming:
You always want to remove any spaces after a ( or [ and any spaces before a ) or a ], and
You won't have (, ), [, or ] inside text literals that you want to leave unchanged (this is really just a subset of #1, but I thought it worth calling out specifically, as it's a big assumption)
...then I don't think nesting is an issue and we can do this with a regular expression. And I don't think you need lookaround at all:
const result = str.replace(/([\[(])\s+|\s+([\])])/g, "$1$2");
// ^^^^^^^^^^ ^^^^^^^^^^
// after opening ( or [ −−−−−−−−/ |
// before closing ) or ] −−−−−−−−−−−−−−−−−−/
The trick there is that we use two captures, and then use both in the replacement; one of them will always be "" while the other will be "(", "[", ")", or "]".
Example:
const str = `check IN [ "[hello world]*" ] OR host IN ( abc,123)`;
const result = str.replace(/([\[(])\s+|\s+([\])])/g, "$1$2");
// ^^^^^^^^^^ ^^^^^^^^^^
// after opening ( or [ −−−−−−−−/ |
// before closing ) or ] −−−−−−−−−−−−−−−−−−/
document.getElementById("before").textContent = str;
document.getElementById("result").textContent = result;
Before:
<pre id="before"></pre>
After:
<pre id="result"></pre>
I'm currently working within an AngularJS directive and in the template I'm attempting to check if a an instance variable of the Controller is a certain type of string.
Specifically, this string can be anything at all so long as it has an 8-digit number in it.
Passing Examples: "gdbfgihfb 88827367 dfgfdg", "12345678", ".12345678"
The number has to be a solid string of 8 numbers with nothing in between.
I've tried this:
$ctrl.var == /[0-9]{8}/
But it doesn't work for some reason. How do I construct a regex in order to do this?
Thanks
Your regex is fine but the comparison is wrong. You want
/\d{8}/.test($ctrl.var)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
let tests = ["gdbfgihfb 88827367 dfgfdg", "12345678", ".12345678", "nope, no numbers here"],
rx = /\d{8}/;
tests.map(str => document.write(`<pre>"${str}": ${rx.test(str)}</pre>`))
Code:
var first = "gdbfgihfb 88827367 dfgfdg";
var second = "12345678";
var third = ".12345678";
var reg = new RegExp('[0-9]{8}');
console.log(first.match(reg));
console.log(second.match(reg));
console.log(third.match(reg));
Output:
[ '88827367', index: 10, input: 'gdbfgihfb 88827367 dfgfdg' ]
[ '12345678', index: 0, input: '12345678' ]
[ '12345678', index: 1, input: '.12345678' ]
How can I check if my data string begins with a punctuation mark using Javascript? I looked at Check if string is a punctuation character and How to know that a string starts/ends with a specific string in jQuery? and a number of others, but I can't tell where I'm going wrong.
Here's a snippet of what I have so far:
var punctuations = [".", ",", ":", "!", "?"];
if (d.endContext.startsWith(punctuations)) {console.log(d.endContext)
} else {console.log('false')};
I only get 'false' returns, but if I pass in "." in
if(d.endContext.startsWith('.'))
...
I get correct results. I also tried
String punctuations = ".,:;?!"
like Check if string is a punctuation character suggested, but both Chrome and Firefox gave me error messages ("Uncaught Syntax Error: Unexpected Identifier" and "SyntaxError: missing ; before statement", respectively). It seemed like that error was usually for writing multiline strings in Javascript, which I don't think I'm trying to do. d.endContext will print multi-line strings, but it works fine when I just pass ".", so I don't think that's the issue.
using Regex is much simpler.
var str = '.abc'
var result = !!str.match(/^[.,:!?]/)
console.log(result)
/ indicates start/end of Regular expression
^ means 'start with'
[] means 'character set'. it will match any characters between [ and ]
!! converts what match returns to a boolean. If it returns a match, it is converted to true. If it returns null, it is converted to false.
Additionally, this app is quite good to learn Regex!
http://regexr.com/
Have a nice day! :D
Use the some and startsWith methods.
punctuations.some(function(character) {
return string.startsWith(character)
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
The some() method tests whether some element in the array passes the test implemented by the provided function.
Or you can also use regex
/[.,:!?]/.test(string.charAt(0))
Using Array.prototype.indexOf is probably the simplest:
var punctuations = [".", ",", ":", "!", "?"];
var stringToSearch = d.endContext; // Your string to search
if (punctuations.indexOf(stringToSearch.charAt(0)) !== -1) {
// Your awesome code goes here
}
It's compatible to IE9 and pretty much all Chrome and Firefox (down to 1.5) versions but if you are using jQuery, you can use inArray for further backwards compatibility.
Or... just for fun you could go the other end, be cutting edge, and break all non-beta browsers with the new ES7 Array.prototype.includes:
var punctuations = [".", ",", ":", "!", "?"];
var stringToSearch = d.endContext; // Your string to search
if (punctuations.includes(stringToSearch.charAt(0))) {
// Your awesome code goes here
}
Compatible with:
Chrome 47 (not yet released)
Firefox 43 (not yet released)
Here's a beautiful solution:
var punctuations = [".", ",", ":", "!", "?"];
var punkyString = ".hello!";
var nonPunkyString = "hello!";
function isPunkyString(str) {
return punctuations.indexOf(str[0]) > -1;
}
console.log(punkyString, "is punky:", isPunkyString(punkyString));
console.log(nonPunkyString, "is punky:", isPunkyString(nonPunkyString));
Unit tests!
var punkyStrings = punctuations.map(function (item) {
return item + " <---<< Punctuations!"
});
var nonPunkyStrings = punctuations.map(function (item, i) {
return i + " <---<< No punctuations!"
});
punkyStrings.forEach(function (item, i) {
console.log("Expect", "isPunkyString(\"" + item + "\")", "to be true:", isPunkyString(item));
});
nonPunkyStrings.forEach(function (item, i) {
console.log("Expect", "isPunkyString(\"" + item + "\")", "to be false:", isPunkyString(item));
});
Why is it beautiful? Because I have used the word punky! :D Oh and I treat the string as an array. Which is nice!
Has anyone else unit tested their code? :D
I have a pattern bellow:
var patt = /((name)|(names)*)/g;
and I have a string for match:
var word = "namesnames";
word is according to pattern logicly, but word.match(patt) return :
["name", "", "name", "", ""]
which is wrong!
i want "namesnames" result from match,
please help me.
thanks.
The problem is that you used (names)*, meaning "names" 0 or more times, when you should have done ((name)(?:s))+, meaning "name" or "names" 1 or more times.
If I understand what you want correctly, you can make it much simpler:
var patt = /(names?)+/g;
This is the stantard string structure:
{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_timestamp":"1325711938","check_hash":"892251599922cc58"}
the only part i need from this string is the numeric value after the "target_profile_id", in this case, would be "100003221104984"
I really suck at regular expressions and any help would be really appreciated !
Thanks in advance
The data appears to be in JSON format (minus HTML escaped). As such, there is no need for a regular expression.
Instead, access it directly:
var data = {"actor":"100003221104984","target_fbid":"286108458103936", ...}
alert(data.target_profile_id);
See the fiddle.
UPDATE
As noted by Jonathan, if the string indeed includes HTML entities, you will need to first parse it to create an object to assign to data in my example above.
There are additional posts on SO that answer how to do that. For example: How to decode HTML entities using jQuery?
If you have all these &quo te; stuff you could also do it by getting the right chars, without regex
var x =
"{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_timestamp":"1325711938","check_hash":"892251599922cc58"}";
var begin = x.indexOf("target_profile_id")+ "target_profile_id".length + "":"".length;
var endString = x.substring(begin, x.length);
var end = endString.indexOf(""") + begin;
alert(x.substring(begin, end));
Try:
/"actor":"(\[^&\]+)/
or
/"actor":"([^&]+)/
I have understood your problem. The whole string is actually a JSON object, where quote(") is present in the form of " ;.
First replace & quote; it with ". Then evaluate the expression and get the value of any item you want.
Below working code :)
<script type="text/javaScript">
var str1="{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_ti":{"actor":"100003221104984","target_fbid":"286108458103936","target_profile_id":"100003221104984","type_id":"17","source":"1","assoc_obj_id":"","source_app_id":"2305272732","extra_story_params":[],"content_timestamp":"1325711938","check_hash":"892251599922cc58"}}";
var ans=str1.split(""").join("\"");
var obj=eval("(" + ans+ ')');
alert(obj.target_profile_id);
</script>
And see how your actual Data looks like:
{
"actor": "100003221104984",
"target_fbid": "286108458103936",
"target_profile_id": "100003221104984",
"type_id": "17",
"source": "1",
"assoc_obj_id": "",
"source_app_id": "2305272732",
"extra_story_params": [],
"content_ti": {
"actor": "100003221104984",
"target_fbid": "286108458103936",
"target_profile_id": "100003221104984",
"type_id": "17",
"source": "1",
"assoc_obj_id": "",
"source_app_id": "2305272732",
"extra_story_params": [],
"content_timestamp": "1325711938",
"check_hash": "892251599922cc58"
}
}