Reputation: 2700
How to use javascript replace with regex in this situation?
<div id="content" style="left: 200px">
=><div id="content" style="left: -200px">
var num = $('#content').attr('style');
alert(num.replace.replace('/[0-9]+/g','-\\$1'));
<div id="content" style="left: -200px">
=><div id="content" style="left: 200px">
var num = $('#content').attr('style');
alert(num.replace.replace('/-[0-9]+/g','\\$1'));
my code seems not work, need a help. thanx.
Upvotes: 0
Views: 132
Reputation:
Just do this :
$('#content').css('left', function (i, value) {
return -parseInt(value);
});
Here is a demo (click the red box) : http://jsfiddle.net/wared/s6M43/.
Upvotes: 1
Reputation: 9368
replace
also takes a function so, you can do something like
var str = '<div id="content" style="left: 200px"> => <div id="content" style="left: -200px">';
str.replace(/(-?)([0-9]+)/g, function(match, sign, px) { return '-' == sign ? px : '-' + px })
//'<div id="content" style="left: -200px"> => <div id="content" style="left: 200px">'
Upvotes: 0
Reputation: 4795
$1
refers to the first capture group - of which you have none. As John says you can use $&
to refer to the entire match.
To use $1
you would need to put ()
around your match to create the capture group /([0-9]+)/g
Upvotes: 1
Reputation: 25421
Use $&
to signify the matched value in the 2nd argument. This is a JavaScript feature of .replace
and not a feature of regular expressions.
var x = "left: 200px".replace(/\d+/,'-$&')
// x == "left: -200px"
Upvotes: 2