...

View Full Version : using replace() to change string



tylerjca
11-11-2006, 07:34 PM
I know how to do the following with PHP:


$text = "<msg>this is a message</msg>";

$text = preg_replace("(<msg>(.*?)</msg>)i","<b>$1</b>",$text);


but how can i do the same with javascript?

ess
11-11-2006, 07:46 PM
Let's assume that you have a string called user_name and contains the value "John Smith"....and you wish to replace Smith with Bond. Here is how.

<script type="text/javascript">

var user_name = "John Smith";

user_name = user_name.replace( "Smith", "Bond" );

</script>

Please note that you can use regular expressions to search for values...

good luck
ess

tylerjca
11-12-2006, 01:41 AM
what you just showed me i know how to do, but i just want the regular expression and replace equivalent for javascript..

david_kw
11-12-2006, 02:16 AM
How about this.



<html>
<head>
<script type="text/javascript">
var text = "<msg>this is a message</msg>";
var reg = /<msg>(.*?)<\/msg>/i;

text = text.replace(reg, "<b>$1</b>");
alert(text);
</script>
</head>
<body>
</body>
</html>


david_kw

P.S. As a side note, does the ? in the reg expression do anything?

liorean
11-12-2006, 02:18 AM
var
re=/<msg>(.*?)<\/msg>/gi,
// Warning on using non-greedy matches.
// They have bad backwards compatibility
// and still don't have quite correct support in JScript
sOrig='<msg>this is a message<\/msg> and <msg>this is another message<\/msg>',
sRes=sOrig.replace(re,'<b>$1<\/b>');

alert(['sRes: '+sRes,'sOrig: '+sOrig].join('\n'));

// Beware! Potential problem:
sOrig='<msg>this is <msg>a message containing a nested<\/msg> message<\/msg> and <msg>this is another message<\/msg>';
sRes=sOrig.replace(re,'<b>$1<\/b>');

alert(['sRes: '+sRes,'sOrig: '+sOrig].join('\n'));

// One possible solution:
sRes=sOrig;
while(re.test(sRes))
sRes=sRes.replace(re,'<b>$1<\/b>');

alert(['sRes: '+sRes,'sOrig: '+sOrig].join('\n'));



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum