Okay, so I have some variables in javascript...
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;
As you can see, I have a link and a position. Using the position var I would like to replace some text in the link field. I would like to strip &pos2=1.teamsp00ky.chat from the link. Naturally, I have to do some basic regular expressions; the problem comes into when I try to use the position var in the regex. I just can't figure it out.
In PHP I could do the following:
preg_replace('/&pos'.$position.'=[^&]*/i', '', $link);
I tried the following in JS, but its not working:
link.replace(new RegExp('&pos'+position+'=[^&]*'), '');
Could someone help me out and tell me what I'm doing wrong? Also, how would I make it case-insensitive?
You need to set the value, not just call the method:
link = link.replace(new RegExp('&pos'+position+'=[^&]*'), '');
To make it case insensitive, use this regex:
new RegExp('&pos'+position+'=[^&]*', "i")
Although it might make it easier if you split the string on the "?", then split up the key/value pairs by "&", and then split them by "=".
Could someone help me out and tell me what I'm doing wrong?
replace does not mutate the string, but returns a new one - you'd have to assign it somewhere.
Also, how would I make it case-insensitive?
Pass the i flag to the RegExp constructor.
link = link.replace(new RegExp('&pos'+position+'=[^&]*', 'i'), '');
<div id="result"></div>
var link = 'http://8wayrun.com/streams/multi?type=3&pos1=1.teamsp00ky.video&pos2=1.teamsp00ky.chat&pos3=1.nycfurby.chat';
var position = 2;
var start = link.indexOf("pos2");
var end = link.indexOf("&", start);
document.getElementById("result").textContent = link.slice(0, start) + link.slice(end + 1);
on jsfiddle
Related
Hello I'm new to javascript and I need a little help with regex/replace
I want to take a url for example (url case 1)
http://url.com/_t_lastUpdate_2670619?location=50457347
or (url case 2)
http://url.com/_t_2670619
I want to select in this case just
_t_2680619
Ignore everything after "?" and before (underscore)t(underscore)
Is it possible with regex/replace? the only thing I managed to do was select numbers only with
var _t__and_number = document.URL.replace(/[^\d]/g, '');
alert(_t__and_number);
But that doesn't solve my problem if there's something like url case 1
(if I could get just the first number even without the (underscore)t(underscore) it would already help me a lot.
Thanks
Solutions:
onetrickpony/michaelb958:
var _t__and_number = window.location.pathname;
alert(_t__and_number);
ermagana:
var _t__and_number = document.URL.replace(/\?.*/g, '').match(/.*\/(.*)/)[1];
alert(_t__and_number);
As suggested by onetrickpony, if this is the URL you are currently browsing, window.location.pathname will yield that part of the URL.
First Part like case (1) and (2)
var s = '//url.com/_t_522121?location=50457347';
var n = s.lastIndexOf('/');
var result = s.substring(n + 1);
alert(result);
n = result.indexOf('?');
result = result.substring(0, n);
alert(result);
If you're trying to pull out the value after the last / and before the ? you could try something like this
url.replace(/\?.*/g, '').match(/.*\/.*(_t_.*)/)[1]
The replace removes everything from the ? and forward, the match creates a group of the values found after the last forward slash which is then accessed by the index 1
Hope this helps.
here is the jsfiddle to show it works:
My JsFiddle
I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.
Ok, I am not sure what is wrong with me, but I am trying to find and replace a portion of multiple URLs.
Basically, I have some URLs that are being dynamically added to my site. All have a class of 'newsLink' some of the links are pulling up google.docs viewer and I need to remove that.
Here is my code thus far:
$('a.newsLink').each(function(){
var lnk = $('a.newsLink').attr();
var re = new RegExp("http://docs.google.com/viewer?url=","g");
lnk.replace(re, "");
});
the links look like:
<a href='http://docs.google.com/viewer?url=myHomePage.pdf' class='newsLink' target='_blank'>
I would like to remove the first part so that the link looks like:
<a href='http://myHomePage.pdf' class='newsLink' target='_blank'>
Anyway, no luck this far...can anyone please help.
First, you are getting all links again inside of the loop. Then, you try to get an attribute, but didn't say which one. Finally, you try to use replace without assigning the return value to anything.
This is what your code should be:
$('a.newsLink').each(function(){
var lnk = this.href;
this.href = lnk.replace("http://docs.google.com/viewer?url=", "");
});
Note: I'm assuming you want the links to become e.g. myHomePage.pdf, without the protocol.
The regular expression you want is.
http:\/\/docs\.google\.com\/viewer\?url=(.+)
First off, this escapes all regular expression characters. In this case \, ., and ?. We are capturing the document using a group that matches every character ((.+)).
So our code looks like this so far.
$('a.newsLink').each(function(){
var lnk = this.href;
var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
this.href = lnk.replace(re, "");
});
Now we get the groups like so.
var match = re.exec(lnk);
This returns an array of the matches. Our document is now stored in match[1]. So our final code comes out to.
$('a.newsLink').each(function(){
var lnk = this.href;
var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
this.href = (re.exec(lnk))[1];
});
I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.
I have a search function, and would like to display the search term in the search input.
My url is: search-1.html?keyword=XXXXXX
How do I get this, and display it in an input?
Thank you in advance.
Use this:
http://ajaxcssblog.com/jquery/url-read-get-variables/
Take luck!
Oh and then you can use the following to display its value in an input field:
$("#inputId").val($.url.param("keyword"));
If it is just one key=value in the url you can use simple regex like this:
var theValueYouWant = window.location.href.match(/keyword=(.+)/)[1]
And set the value of an input like this
$('input').val(theValueYouWant)
If you want to parse the GET string more thoroughly, this function should do it...
gets = {};
$.each(location.search.replace(/^\?/,'').split('&'),function(k,v){
bits = v.split('=');
gets[bits[0]] = bits[1];
});
Regex solution:
var S = window.location.search; // "?keyword=..." etc.
var T = S.match(/^\?(?:[^\b]*&+)?keyword=([^&]*)/);
if (T)
T = T[1]
else
T = "no keywords found"
If multiple values are given for "keyword" (e.x. ?keyword=XXX&keyword=YYY), the regex will only find the first of these values (e.x. XXX). This regex works even if there are other variables in the query string.
jQuery-less solution:
<script type="text/javascript">
var $_GET=[],pairs=location.href.toString().substring(location.href.toString().indexOf("?")+1).split("&");for(key in pairs){pos=pairs[key].indexOf("=");$_GET[pairs[key].substring(0,pos)]=decodeURIComponent(pairs[key].substring(pos+1).replace(/\+/g," "))};
// Now just access with $_GET
// example...
keyword = $_GET["keyword"];
</script>