javascript: extract parts of a string (regex) - javascript

The question is simple, assume the following string:
var str = 'aaaaab\'s'
How do you extract the value of href. I would think something like
var arr = str.match(/(?:href=")(\w+)/g) ;
--> ["href="aaaa", "href="bb"]
Of course I want
["aaaa", "bb"]
Withoug the /g it get close, but it only matches "aaaa". Any suggestions how to fix this ?
Thanks!

DOM parsing with JS is so easy.
var str = 'aaaaab\'s',
help = document.createElement('div');
helper.innerHTML = str;
Array.prototype.forEach.call(help.querySelectorAll("a[href]"), function (elem) {
console.log(elem.getAttribute('href'));
});
http://jsfiddle.net/ExplosionPIlls/gtdFh/

Because Javascript doesn't have lookbehind, this may be what you want. Naturally there will be more elegant solutions:
input.match(/<[^href|/]*(href[\s]*=[\s]*")([^"]+)(?=">)/g).map(
function(x){return x.split('href')[1].replace(/[^"]+"(.*)/,'$1');
})
Additionally, you may be better off getting a HTML parsing plugin. And extracting the properties you need using that.
Cheers.

Related

Replace function not working with javascript

How can I strip the $ and , characters from the following value, the code i am using is not working
var asset_value = second_col.find("input[type=text]").val().replace('$', '');
second_col.find("input[type=text]").val() looks like
$1,080.00
Update:
I am not sure why i am getting voted down! the duplicate solution does not solve my question, nor does any answer below, except for this, very strange!
second_col.find("input[type=text]").val(function(i, val) {
return val.replace(/\$|,/g, '');
});
var asset_value = second_col.find("input[type=text]").val();
You can use regex for this:
second_col.find("input[type=text]").val().replace(/[\$,]/g,'').
Assign this value to variable and use it.

using javascript to replace onpage javascript

I'm fairly new to javascript so please go easy on me,
I have this code on a webpage:
<script type="text/javascript"> bb1 = "oldcode"; bb2 = "morecodehgere"; bb3 = 160000;</script>
I want to replace 1% of all page loads oldcode to newcode
There are multiple instances of this code on the same page and I want to replace them all.
window.onload = replaceScript;
function replaceScript() {
var randomNumber = Math.floor(Math.random()*101);
var toReplace = 'oldcode';
var replaceWith ='newcode';
if randomNumber == 1 {
document.body.innerHTML = document.body.innerHTML.replace(/toReplace/g, replaceWith);
}
}
This is the current code I've got but it doesn't work.
Is javascript the bast way to achieve what I'm looking to do? If so whats the best way to do this?
The regular expression literal:
/toReplace/g
will create a regular expression object that matches the string "toReplace". If you want to create a regular expression to match the (string) value of the variable toReplace, you must use the RegExp constructor:
var re = new RegExp(toReplace, 'g');
It is not a good idea to replace the innerHTML of the body with a copy of itself. The innerHTML property doesn't necessarily reflect all the nuances of the DOM and will not include things like dynamically added listeners. It also varies from browser to browser.
Using a regular expression to replace parts of innerHTML is almost certain to produce unpredictable results, it may work well on trivial pages but will not be reliable on complex pages.

Having issues with a replace function in Javascript

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

Regular Expression in indexOf on javascript

I want get my program parameters from rel attribute of element, first of all is it logical ?
and the rel attribute may contain this string rel="_p|b|w=300|h=200" or rel="_p|w=300"
, so I use split to split my string with | pattern :
var attr = $(this).attr('rel').split('|');
for _p and b there is no problem because I can check with indexOf but for w and h I should use regular expression because the w and h value will be change.
how can I use regular expression in indexOf ?
sorry for my bad English
EDIT:
if (attr.indexOf('b')) {
blank = true;
}
First of all, that isn't a very elegant way of retrieving data. Anyway, if you really want to do that in that way, then you can use regexes as follows:
var matches = $(this).attr('rel').match(/w=(\d+)/);
var w = (matches && matches[1]) || defaultValue;
Also, if there can be multiple elements that end in 'w', then you'd better change your regex to something like:
var matches = $(this).attr('rel').match(/(?:^|\|)w=(\d+)/);
I would have suggested the use of custom attributes as well, however these would not be w3-conform as you want them to.
A simple way would be to split the parameters and then loop through and check each index whether it is one of the attributes you are expecting:
var cust_params = $(this).attr('rel').split('|'); //or this.rel as GGG suggested in a comment?
for(var i=0;i<cust_params.length;i++) {
if('_p'==cust_params[i]) {
//...
}
//...
if(cust_params[i].match(/w=(\d+)/)) {
//you could even do this without a regular expression
}
}
I hope this doesn't violate some good practice that I'm unaware of because I always feel like there must be a more elegant way when I do this kind of thing :) As it is I get a kind of quick-and-dirty feel about this.
Sorry there is no way you can do it in one command with normal javascript, indexOf just doesn't support regular expression.
You can either loop through the array or use jquery supported command for array.
For example: once you have the array attr as you like, you can use jQuery.grep() http://api.jquery.com/jQuery.grep/
a_equal = jQuery.grep(attr, function(a, i){
return (a.match(/=/) and i > 0); // modify this as you like
});
to create an array a_equal with all the assignment argument.
disclaimer.. code not yet tested.
Like Paolo Bergantino I'd also suggest using data-attributes, or you could store the data in a JSON (again, in a data attribute) and parse that:
<a href="#" data-info='{"width": "300", "height": "200", "color": "#fff", "etc": "foo"}'>
var info = JSON.parse(a.getAttribute('data-info'));
Edit: replaced eval with Phrogz's suggestion.
(With eval: eval('(' + a.getAttribute('data-info') + ')'))

Quotes in Javascript

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.

Categories

Resources