Connecting Tech Pros Worldwide Help | Site Map

about javascript replace

luckcape@gmail.com
Guest
 
Posts: n/a
#1: Jun 29 '06
hi all, i encountered a problem when using js replace.

I wanna get the value of an attritbute from xml by using the following
code,

var str = 'id="1" type="1" cn="" disc="sdfgdsgdgsdg">';
var Attribute = "id";
var Attr = new RegExp(".*" + Attribute + '="([^"]*)".*>');
alert(str.replace(Attr, "$1"));

it works fine, the message dialog shows "1".

but if the str contain "\r\n",

var str = 'id="1" type="1" cn="" disc="sdfgdsgdgsdg\r\n">';
var Attribute = "id";
var Attr = new RegExp(".*" + Attribute + '="([^"]*)".*>');
alert(str.replace(Attr, "$1"));

then the message dialog shows whole original str.

Can anyone give me some advice?

Lasse Reichstein Nielsen
Guest
 
Posts: n/a
#2: Jun 29 '06

re: about javascript replace


luckcape@gmail.com writes:
[color=blue]
> I wanna get the value of an attritbute from xml by using the following
> code,
>
> var str = 'id="1" type="1" cn="" disc="sdfgdsgdgsdg">';
> var Attribute = "id";
> var Attr = new RegExp(".*" + Attribute + '="([^"]*)".*>');
> alert(str.replace(Attr, "$1"));
>
> it works fine, the message dialog shows "1".[/color]
....[color=blue]
> but if the str contain "\r\n",
>
> var str = 'id="1" type="1" cn="" disc="sdfgdsgdgsdg\r\n">';[/color]
....[color=blue]
>
> then the message dialog shows whole original str.[/color]

Because ".*" doesn't match the "\n", the regular expression doesn't
match the string at all. So, you replace all matches (none) of the
regexp with something, which doesn't change the string.

/L
--
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Closed Thread