[Javascript] complex replacement with RegExp

Paul Novitski paul at novitskisoftware.com
Fri May 7 19:04:22 CDT 2004


Can someone help me compose a regular expression to perform this logic:

	if S contains A
		replace A with B
	else if S contains B
		replace B with A

Right now I'm using this Javascript logic:

var rgEN = /(^|\s)en(\s|$)/	// finds English
var rgES = /(^|\s)es(\s|$)/	// finds Spanish

var sClass = "enten en enten"	// test string

	if (rgEN.test(sClass)) var sClass = sClass.replace(rgEN, " es ")
	else
	if (rgES.test(sClass)) var sClass = sClass.replace(rgES, " en ")

This example successfully replaces "en" and isn't fooled by "enten".

However, I'm hoping I can replace all that with a single replace() statement.

My application is that I'm toggling between two language codes embedded in 
a className.  I've developed & tested this RegExp to locate either language 
code as a discrete word in space-delimited string of words:

	/(^|\s)(en|es)(\s|$)/

This tests true if the string contains either "en" or "es" delimited by 
whitespace or the start or end of the string, and will successfully find my 
target language codes in any of these strings:

	"en"
	"xx en"
	"en xx"
	"xx en xx"
	"enten en enten"	(ignores "enten")

I know how to do a crude replacement:

	var rg = new RegExp(/(^|\s)(en|es)(\s|$)/)
	var sAfter = sBefore.replace(rg , " XX ")

but I don't know how to replace (A with B) or (C with D) in a single 
statement.  Is this possible?

Secondary issue:  My logic only replaces one language code with another.  I 
also need to cover the possibility that neither occurs, in which case I 
want to concatenate " en" to the className.  Can RegExp test for no-match 
and append a string, or do I have to wrap it in Javascript logic
	if (!rg.test(sClass)) sClass += " en"
to accomplish that?

Tertiary issue:  Right now I'm having to replace my target strings with 
text surrounded by spaces (e.g., " es ") because my RegExp searches for and 
therefore replaces any preceding or following whitespace.  Can I replace 
just the en|es characters and not the surrounding whitespace?

Thanks,
Paul 





More information about the Javascript mailing list