Forums
This topic is locked
asp javascript replace function
Posted 06 Jul 2005 16:42:43
1
has voted
06 Jul 2005 16:42:43 Michael Behan posted:
I've been making good use of the asp javascript replace function (something.replace("this","that". but so far I can only replace the first instance of a string and can only replace exact case sensitive matches. Using regular expressions I've been able to do a replace all, but not when i want to do something like replace all the hello's (or HeLlO's) with goodbyes's etc.
Can this be done?
Replies
Replied 15 Jul 2005 17:29:10
15 Jul 2005 17:29:10 myke black replied:
try this:
<pre id=code><font face=courier size=2 id=code>
var string1 = "hello my name is bob. Hello bob. heLLO my name is kate HELLO kate"
var string2 = replaceAll(string1,"Hello","goodbye",false)
Response.Write("string 1 = " [add] string1)
Response.Write("<br>"
Response.Write("string 2 = " [add] string2)
function replaceAll(strSource,lookFor,replaceWith) {
strLowerCase = strSource.toLowerCase();
lookForLower = lookFor.toLowerCase();
while(strLowerCase.indexOf(lookForLower) != -1) {
posStart = strLowerCase.indexOf(lookForLower)
posEnd = posStart [add] lookFor.length
strLowerCase = strLowerCase.substring(0,posStart) [add] replaceWith [add] strLowerCase.substring(posEnd,strLowerCase.length)
strSource = strSource.substring(0,posStart) [add] replaceWith [add] strSource.substring(posEnd,strSource.length)
}
return strSource
}
</font id=code></pre id=code>
replace [add] with plus sign.
This will replace all the instances of 'hello' with 'goodbye' but will not preserve the case.
p.s. How do we write a plus sign in code in these forums?
<pre id=code><font face=courier size=2 id=code>
var string1 = "hello my name is bob. Hello bob. heLLO my name is kate HELLO kate"
var string2 = replaceAll(string1,"Hello","goodbye",false)
Response.Write("string 1 = " [add] string1)
Response.Write("<br>"
Response.Write("string 2 = " [add] string2)
function replaceAll(strSource,lookFor,replaceWith) {
strLowerCase = strSource.toLowerCase();
lookForLower = lookFor.toLowerCase();
while(strLowerCase.indexOf(lookForLower) != -1) {
posStart = strLowerCase.indexOf(lookForLower)
posEnd = posStart [add] lookFor.length
strLowerCase = strLowerCase.substring(0,posStart) [add] replaceWith [add] strLowerCase.substring(posEnd,strLowerCase.length)
strSource = strSource.substring(0,posStart) [add] replaceWith [add] strSource.substring(posEnd,strSource.length)
}
return strSource
}
</font id=code></pre id=code>
replace [add] with plus sign.
This will replace all the instances of 'hello' with 'goodbye' but will not preserve the case.
p.s. How do we write a plus sign in code in these forums?