How to get the ID from this URL? - javascript

I need a way to get the ID ( 153752044713801 in this case ) of this page:
https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801
I tried this code but doen't work:
var str = 0, pagefb = 0;
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var re1 = /^(.+)facebook\.com\/pages\/([-\w\.]+)\/([-\w\.]+)/;
if(re1.exec(fburl)){
str = re1.exec(fburl)[3];
pagefb = str.substr(str.lastIndexOf("-") + 1);
alert('ok');
}

try:
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split("/");
var myId = parts[parts.length-1];
alert(myId);

Try this regular expression: ^(.+)facebook\.com\/pages\/.*\/(\d*)
(in JavaScript, you have to add "/" at the beginning and end of the pattern like you did before)

this works for me
fburl.split('/')[fburl.split('/').length-1]

You can split the string using .split("/"). More information is availible on MDN
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
Basically it returns an array of the string split into multiple parts (at the character/s you put inside the brackets).
The parts[parts.length - 1] will get the last item in the array parts
Demo below (Don't worry about the document..., they just print out data):
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713‌​801/?ref=sfhsidufh';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
// If first digit is ?
if (myFacebookId[0] == '?') {
// Set myFacebookId to the second from last part
myFacebookId = parts[parts.length - 2]
}
document.write('MyFacebookId: ' + myFacebookId)

Related

JavaScript Split, Split string by last DOT "."

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf

Using Javascript RegExp object

I must have a syntax error in my code but I can't see it. fiddle here
var comma = ',,';
var stop = '.。';
var expression = '/[]+/';
expression = expression.substr(0,2) + comma + stop + expression.substr(2);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
}
I'm expecting res.length to be 3 but it is always 1 and returns the full string. What am I missing?
/ is used as delimiter for RegExp literal. e.g. /[a-zA-Z]/g
/ is not needed when you pass a pattern to the RegExp constructor. e.g. new RegExp('[a-zA-Z]', 'g')
To resolve the problem, remove the / (and modify the rest of your code):
var expression = '[]+';
Or you can just pass a RegExp literal directly:
var res = "foo,吧。baz".split(/[,,.。]+/g);
When you creat your Regex you're using this: var expression = '/[]+/';. The / delimiters are for use when you're delaring a regex like this:
var expression = /[]+/; // note: no quotes.
You're using new Regexp(), so they're not required in your string. Removing them gives this:
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}
Which does what you expect. See this fiddle. I've adjusted the string indices and the loop index so that things work...
var expression = '/[]+/';
Should be
var expression = '[]+';
Also, adjust the substring indices accordingly
http://jsfiddle.net/2Pbm3/4/
Working like this :
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}

JavaScript regex using a character twice

So I'm using regex to grab information from a string, the issue is I need to both start up and stop at a / in the string.
Here's an example
var regexp = /\/(.*?)=(.*?)\//g;
var url_hash = "/s=lorem+ipsum/p=2/";
var match;
var result = {};
while ((match = regexp.exec(url_hash)) != null) {
result[match[1]] = match[2];
}
I can grab result['s'] without issue, but grabbing result['p'] becomes problematic, because the ending / for result['s'] is the same as the starting / for result['p']. If I changed the string to /s=lorem+ipsum//p=2/ it works perfectly, but of course that's hideous. So how can I fix this so that it both ends and starts up at the /? I'm stuck, any help is appreciated.
Use this regex:
/\/([^/=]+)=([^/]+)/
Code:
var regexp = /\/([^/=]+)=([^/]+)/g;
var url_hash = "/#!/s=lorem+ipsum/p=2/";
var match;
var result = {};
while ((match = regexp.exec(url_hash)) != null) {
result[match[1]] = match[2];
document.writeln(match[1] + ' = ' + match[2] + '<br>');
}
OUTPUT:
s = lorem+ipsum
p = 2
Online demo of the code
Why can't you just split it?
var result = {};
var url = "/#!/s=lorem+ipsum/p=2/".slice(4, -1).split('/');
for (i in url) {
var value = url[i].split('=');
result[value[0]] = value[1];
}
console.log(result);
You can determine the look-ahead set for part after the = yourself instead of adding it to the regular expression. The look-ahead set is "everything but a forward slash".
var regexp = /\/(\w+)=([^/]+)/g;
Btw, I'm assuming that the part before the = is word-like (i.e. alphanumeric)

How can i match and replace a string and its before one letter in javascript?

var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var word = '[BACK]';
var substrings = str.split(word);
var cnt= substrings.length - 1;
for(var i = 0;i<cnt;i++){
str = str.replace(/.{1}\[BACK\]{1}/i,""); //remove backspace and one character before it.
}
The above script returns something like "[BACK it's a test string" I need to get this result as "it's a test string" please help me....
It's easier to do this without a regex actually.
String.prototype.replaceFromIndex=function(index, length, replace) {
return this.substr(0, index) + replace + this.substr(index+length);
}
var search = '[BACK]';
var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
while((index = str.indexOf(search)) >= 0){
str = str.replaceFromIndex(index-1, search.length+1, '');
}
alert(str);
Check http://jsfiddle.net/fRThH/2/ for a working example.
Wrap it in a function and you are ready to go!
Courtesy to Cem Kalyoncu ( https://stackoverflow.com/a/1431113/187018 ) for a slightly modified version of String.prototype.replaceAt
My idea is to count all the backspaces [BACK] and then replace them with an empty string one by one:
var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var backspaces = str.match(/\[BACK\]/g).length;
for(i=0; i<backspaces; i++)
{
str = str.replace(/.?\[BACK\]/, '');
}
document.write( str );
working example: jsFiddle
If I understood correctly
var dat = str.split('[BACK]').filter(function(e){return e})[1];
here is the working demo.
One of the problems that I found out was that you didn't set a condition in which you would not have to remove the first character when the string '[BACK]' is in position zero.
Well, the solution I am posting here first search for the position of the first '[BACK]' string, and then creates a substring of the characters that we want to remove, so, if there is a character before the string '[BACK]', it is included in the substring. Then, the substring is removed from the main string, and it continues looping until all the '[BACK]' s are removed.
var str = "itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var word = '[BACK]';
var substrings = str.split(word);
var cnt = substrings.length - 1;
for (i = 0; i < cnt; i++) {
pos = str.search("[BACK]");
if (pos - 1 > 0) {
str = str.replace(str.substring(pos - 2, pos + 5), '');
} else {
str = str.replace(str.substring(pos - 1, pos + 5), '');
}
}
Here is the code in jsfiddle:

String to array then remove last element

I have the strings below and I am trying to remove the last directory from them but I cant seem to get the grasp of it.
JavaScript
var x = path.split("/")
alert(path +' = ' +x.slice(0, -1));
Expected Result
/foo/bar/ = /foo/
/bar/foo/ = /bar/
/bar/foo/moo/ = /bar/foo/
Try:
let path = "/bar/foo/moo/";
let split = path.split("/");
let splicedStr = split.slice(0, split.length - 2).join("/") + "/";
console.log(splicedStr);
Try:
var sourcePath="/abc/def/ghi";
var lastIndex=sourcePath.lastIndexOf("/");
var requiredPath=sourcePath.slice(0,lastIndex+1);
Output: /abc/def/

Categories

Resources