Using javascript replace to replace numbers in a s

2019-05-26 01:37发布

问题:

I have a string

var x='abcdefg1234abcdefg';

I want to replace 1234 with 555 using the x.replace() function like

x=x.replace(stuff here)

I tried to pass '1234','555' as the parameters but it's not working.

Any clues? thanks

Edit: The string is in a hidden <input> field. The value of it is:

<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="400" height="385">
 <param name="movie" value="player.swf" /> <param name="allowfullscreen" value="true" />
 <param name="allowscriptaccess" value="always" />
 <param name="flashvars" value="provider=http&file=files/videos/10.file" />
 <embed type="application/x-shockwave-flash" src="player.swf" width="400" height="385" allowscriptaccess="always" allowfullscreen="true" flashvars="provider=http&file=files/videos/10.file&image=preview.jpg"/>
</object>

I want to replace the width value and the height value to values stored in sb_width and sb_height.

回答1:

What you've described should have worked:

var x = 'abcdefg1234abcdefg';
x = x.replace('1234', '555');
alert(x); // alerts abcdefg555abcdefg

But note that replace when given a string will only replace the first one. To replace more, use a regex with the g flag (for "global"):

var x = 'abcdefg1234abcdefg1234xxx';
x = x.replace(/1234/g, '555');
alert(x); // alerts abcdefg555abcdefg555xxx

Live example



回答2:

following code works, tried now:

var bla='dfasfdas123dfasfas';
alert(bla.replace('123','555'));

Tried debugging in firebug or sth? Give us the exact code snippet you are trying



回答3:

Ok, this isn't string replacement at all. You use jQuery I hope?

$("$player").attr("width", sb_width);
$("$player").attr("height", sb_height);

$("$player").children("embed").attr("width", sb_width);
$("$player").children("embed").attr("height", sb_height);

String replacement is not the way to go here. You'd need to hardcode the initial values, might replace an unintended similar string, the code doesn't really communicate your intention (to change height/width, not to manipulate strings)