JS remove everything after the last occurrence of a character [duplicate] - javascript

This question already has answers here:
Remove everything after last backslash
(3 answers)
Closed 9 months ago.
Okay I have this
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(URL.lastIndexOf("/")));
Gives you "/remove-everything-before-the-last-occurrence-of-a-character"
How do I get "http://stackoverflow.com/questions/10767815/"

Here you are:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
Hope this helps.

Seems like a good case for a regular expression (can't believe no one has posted it yet):
URL.replace(/[^\/]+$/,'')
Removes all sequential non–forward slash characters to the end of the string (i.e. everything after the last /).

Generic solution
This is a generic function that also handles the edge case when the searched character or string (needle) is not found in the string we are searching in (haystack). It returns the original string in that case.
function trimStringAfter(haystack, needle) {
const lastIndex = haystack.lastIndexOf(needle)
return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1)
}
console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/
console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd', '/')) // abcd/
console.log(trimStringAfter('abcd', '/')) // abcd

var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(0,URL.lastIndexOf('/')+1));
//The +1 is to add the last slash

Try this jsfiddle or run the code snippet.
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var myRegexp = /^(.*\/)/g;
var match = myRegexp.exec(URL);
alert(match[1]);

console.log(URL.substring(0, URL.lastIndexOf("/")+1));

Run this:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var temp = URL.split('/');
temp.pop();
var result = temp.join('/');
alert(result);

Try utilizing .match() with RegExp /^\w+.*\d+\//
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var res = URL.match(/^\w+.*\d+\//)[0];
document.body.textContent = res;

Try an array based extraction like
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
snippet.log(URL.split('/').slice(0, 5).join('/'));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Related

How can I do string replace in jquery [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I have this code
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(" ", "-");
$("#newsurl").val(res);
});
to replace spaces into dash to get URL like this
wordone-wordtow-wordthree
but i have problem with this code it's just replace first space like this
wordone-wordtow wordthree
How can i solve this problem
You need to do a global match, you can do this with a regex
var res = titleval.replace(/\s/g, "-");
Though String.prototype.replace does support having flags passed, this is deprecated in firefox and already doesn't work in chrome/v8.
Alternate method (if regex is not mandatory) could be to split and join
var res = titleval.split(" ").join("-");
or
var res = titleval.split(/\s+/).join("-");
Use regex with global flag
titleval.replace(/\s/g, "-");
try like this:
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(/\s+/g, '-');
$("#newsurl").val(res);
});

How do i match text after a specific character?

I have a url that looks like this:
http://mysite/#/12345
How do I retrieve the text using regex after the /#/ which is essentially a token that I would like to use elsewhere in my javascript application?
Thanks.
You don't need regex here, just String#substr using String#indexOf:
var s = 'http://mysite/#/12345';
var p ='/#/'; // search needle
var r= s.substr(s.indexOf(p) + p.length);
//=> 12345
Let the browser do it for you
var parser = document.createElement('a');
parser.href = "http://mysite/#/12345";
alert(parser.hash.substring(2)); //This is just to remove the #/ at the start of the string
JSFiddle: http://jsfiddle.net/gibble/uvhqa4yv/
Try with JavaScript String methods.
var str='http://mysite/#/12345';
alert(str.substring(str.lastIndexOf("/#/")+3));
You can try with String'smatch() method as well that uses regex expression.
Just get the matched group from index 1 that is captured by enclosing inside the parenthesis (...)
var str='http://mysite/#/12345';
alert(str.match(/\/#\/(.*)$/)[1]);
Using the browser to parse the URL and getting the hash would probably be most reliable and would work with any valid URL
var url = 'http://mysite/#/12345';
var ele = document.createElement('a');
ele.href = url;
var result = ele.hash.slice(2);
FIDDLE
or you can just split and pop it
var result = url.split('#/').pop();

Regex javascript + replace

I got few lines like these:
/coc59409.p?id=1218405784092
/acme-made-skinny-lray-orange/5616664.p?id=1218679205878
/incase-campus-brk-gray-pink-berry/7209107.p?id=1218833962192&skuId=7209107
and I need to delete in all of them what come after this ".p?id="
how can I do that?
results :
/coc59409.p?id=
/acme-made-skinny-lray-orange/5616664.p?id=
/incase-campus-brk-gray-pink-berry/7209107.p?id=
=> "/coc59409.p?id=1218405784092".replace(/\?.*$/,"")
>> "/coc59409.p"
You don't need a regular expression here - contextually what you are referring to is the query string of the URL and there are already tools in the DOM with the facility to tokenise this, for example:
var url = '/coc59409.p?id=1218405784092',
a = document.createElement('a');
a.href = url;
console.log( a.pathname ); // '/coc59409.p'
Details about the HTMLAnchorElement can be found here.
You could just split it,
var url = '/acme-made-skinny-lray-orange/5616664.p?id=1218679205878'
var urlArr = url.split('=');
console.log(urlArr[0]+'=');
Hope that helps :)
Take each line and replace id=[THE REST OF THE LINE] with id=.
Like so:
"coc59409.p?id=1218405784092".replace(/id=(.*)$/, 'id=')

Extracting a URL parameter with JavaScript [duplicate]

This question already has answers here:
Get escaped URL parameter
(19 answers)
Closed 8 years ago.
I have a URL:
http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382
Edit: I should also not the url is stored in a variable and I want it to work something like this:
$(".videothumb a").live('click', function() {
var URL = < do something to cut the string >
console.log(URL);
return false;
});
And I want to cut the URL starting from "=" and ending at "&" so I'll end up with a string like this: "JssO4oLBm2s".
I only know of the slice() function but I believe that only takes a number as beginning and end points.
Using .split() will give a position based solution which will fail the order of parameters changes. Instead I think what you are looking for is the value of parameter called v for that you can use a simple regex like
'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.match('[?&]v=(.*?)(&|$)')[1]
Try
'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'
.split('=')[1] // 'JssO4oLBm2s&list'
.split('&')[0] // 'JssO4oLBm2s'
Or, if you want to be sure to get the v parameter,
var v, args = 'http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382'.split("?")[1].split('&');
for(var i = args.length-1; i>=0; --i) {
var data = args[i].split('=');
if(data[0]==='v') { v = data[1]; break; }
}
Use .split(). Separated to 2 lines for clarity
var first = "http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".split('=')[1]
var result = first.split('&')[0]; //result - JssO4oLBm2s
v = 'JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382';
var vamploc = v.indexOf("&");
vstring = v.substr(0, vamploc);
You can play with the code a bit to refine it, but the general concepts work.
use Regexp (?:v=)(.+?)(?:&|$)
Fiddle DEMO
"http://www.youtube.com/watch?v=JssO4oLBm2s&list=PLGHJ4fVazTpYRZTEhqgurtSH6XlDMIEJM&shuffle=382".match('(?:v=)(.+?)(?:&|$)')[1]
Reference
http://gskinner.com/RegExr/

Remove last element from url

I need to remove the last part of the url from a span..
I have
<span st_url="http://localhost:8888/careers/php-web-developer-2"
st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook"
st_processed="yes"></span></span>
And I need to take the st_url and remove the php-web-developer-2 from it so it is just http://localhost:8888/careers/.
But I am not sure how to do that. php-web-developer-2 will not always be that but it won't have any / in it. It will always be a - separated string.
Any Help!!??
as simple as this:
var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
url = url.substring(0, to);
Here is a slightly simpler way:
url = url.slice(0, url.lastIndexOf('/'));
$('span').attr('st_url', function(i, url) {
var str = url.substr(url.lastIndexOf('/') + 1) + '$';
return url.replace( new RegExp(str), '' );
});
DEMO
Use this.
$('span').attr('st_url', function(i, url) {
var to = url.lastIndexOf('/') +1;
x = url.substring(0,to);
alert(x);
})​
You can see Demo
You could use a regular expression to parse the 'last piece of the url':
var url="http://localhost:8888/careers/php-web-developer";
var baseurl=url.replace(new RegExp("(.*/)[^/]+$"),"$1");
The RegExp thing basically says: "match anything, then a slash and then all non-slashes till the end of the string".
The replace function takes that matching part, and replaces it with the "anything, then a slash" part of the string.
RegexBuddy has a great deal of information on all this.
You can see it work here: http://jsfiddle.net/xKxLR/
var url = "http://localhost:8888/careers/php-web-developer-2";
var regex = new RegExp('/[^/]*$');
console.log(url.replace(regex, '/'));
First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .

Categories

Resources