0

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.

0

4 Answers 4

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

$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

2 Comments

I had no idea you can use capture groups. That is insanely useful.
I on the other hand only discovered $& a few hours ago ;)
1

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/.

Comments

0

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">'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.