Ask Ben: Javascript String Replace Method

Posted July 17, 2006 at 7:36 AM

Tags: Javascript / DHTML, Ask Ben

How do I use the Javascript string replace method? I don't know much about regular expressisons, but I can seem to get is sort of working without them?

There is no single question here. The above question is just one of MANY questions that I get from a lot of people about using the Javascript replace method that is built into the Javascript String object. The following should hopefully address all of their questions at one time.

First, we have to create a little text blurb on which to perform our Javascript string replace testing.

 Launch code in new window » Download code as text file »

  • var strText =
  • "I saw this girl walking down the street the\n" +
  • "other day as I was leaving work. She had calves\n" +
  • "that were crazy large; so big and round. The kind\n" +
  • "of calves that you'd want to get down on your hands\n" +
  • "and knees just to touch.";

When doing a simple string replace, only the first instance of the matching string will be replaced.

 Launch code in new window » Download code as text file »

  • alert( strText.replace( "th", "[X]" ) );

If you want to replace more than the first instance, you can start looping over the string making replacements until the target string can no longer be found in the string value.

 Launch code in new window » Download code as text file »

  • var strReplaceAll = strText;
  • var intIndexOfMatch = strReplaceAll.indexOf( "th" );
  •  
  • // Loop over the string value replacing out each matching
  • // substring.
  • while (intIndexOfMatch != -1){
  • // Relace out the current instance.
  • strReplaceAll = strReplaceAll.replace( "th", "[X]" )
  •  
  • // Get the index of any next matching substring.
  • intIndexOfMatch = strReplaceAll.indexOf( "th" );
  • }
  •  
  • alert( strReplaceAll );

Notice that the replace method is CASE SENSITIVE. It went through and replaced out all of the "th" instances, but did not replace anything with an upper case T (ex. The). Looping over the indexes is a bit of pain in the butt. If you are intending to do this type of operation a lot, you might want to consider building a replaceAll() method into the Javascript String object as a prototype method so that it would be available to all strings.

 Launch code in new window » Download code as text file »

  • // Replaces all instances of the given substring.
  • String.prototype.replaceAll = function(
  • strTarget, // The substring you want to replace
  • strSubString // The string you want to replace in.
  • ){
  • var strText = this;
  • var intIndexOfMatch = strText.indexOf( strTarget );
  •  
  • // Keep looping while an instance of the target string
  • // still exists in the string.
  • while (intIndexOfMatch != -1){
  • // Relace out the current instance.
  • strText = strText.replace( strTarget, strSubString )
  •  
  • // Get the index of any next matching substring.
  • intIndexOfMatch = strText.indexOf( strTarget );
  • }
  •  
  • // Return the updated string with ALL the target strings
  • // replaced out with the new substring.
  • return( strText );
  • }

Now, replaceAll() is a built in method for all string values. Try performing the same replace we did above, but use this built in method instead.

 Launch code in new window » Download code as text file »

  • strReplaceAll2 = strText.replaceAll( "th", "[X]" )
  •  
  • alert( strReplaceAll2 );

You will see that it does the same replace with much less code! Not only that, every string value in you application can leverage the replaceAll() method once the prototype has been defined.

As you saw above though, the replace is still case sensitive. If you wanted to build a case INSENSITIVE replace, you could do so using a modification of the logic above. But, this would get very hairy very fast. Instead, you can use a regular expression (often referred to as a RegEx or a RegExp). Regular expressions are much more powerful than standard string matching as they can use very complicated logic.

 Launch code in new window » Download code as text file »

  • // Let's take a look at the above example using regular expressions.
  • strReplaceSimple = strText.replace( new RegExp( "th", "" ), "[X]" );
  •  
  • alert( strReplaceSimple );

As you can see, we have the same replace happening. So let's take a look at what's going on. Instead of passing simple target string to the replace() method, we are passing in a regular expression (new RegExp()) object instance. The RegExp() takes two arguments, the expression and the search flags (left blank in our example). There are two universally valid flags: [g] which means globally replace and [i] which
means case INsensitive. By default, the regular expression is NOT global and case sensitive.

 Launch code in new window » Download code as text file »

  • // So let's try to do a global replace using regular expressions.
  • strReplaceAll = strText.replace( new RegExp( "th", "g" ), "[X]" );
  •  
  • alert( strReplaceAll );

We just did a global replace in ONE line of code. Compare this to the non-regular expression solution which takes 13 lines of code (I am including line breaks and white space in the count). Now for the magic... let's do that same thing with out case sensitivity.

 Launch code in new window » Download code as text file »

  • strReplaceAll = strText.replace( new RegExp( "th", "gi" ), "[X]" );
  •  
  • alert( strReplaceAll );

We just replaced out that additional "Th" simply by adding the flag [i] into the regular expression. That's how powerful regular expressions are. But there's more. Regular expressions are more than just flags. Much more!

Image that for some reason, you knew about regular expressions, but you didn't know about the case insensitive flag [i]. You could have performed the same replace using this:

 Launch code in new window » Download code as text file »

  • strReplaceAll = strText.replace( new RegExp( "(T|t)(H|h)", "g" ), "[X]" );
  •  
  • alert( strReplaceAll );

This groups the two letters together, and for each letter it tells the replacing algorithm to match t OR T followed by h OR H. There is sooo much more that regular expressions can do. Unfortunately, that is outside the scope of this entry. You should really look into regular expression both in Javascript and in ColdFusion / Java. They are amazing.

But what happens if you don't want to do a simple replace? The replace method allows some very interesting flexibility. Up until now, we have been passing a simple string in a the "replace-in" argument ([X]). But, you don't have to. You can pass in a function pointer instead.

For this example, let's replace out the target string with a random letter in the brackets, not necessarily the X. First we have to create a function that will return the resultant random string.

 Launch code in new window » Download code as text file »

  • function RandomString(){
  • // Create an array of letters.
  • var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
  •  
  • // Use the random() method and the modulus (%) operator to
  • // pick a random letter from the above array.
  • var intLetter = (Math.floor( Math.random() * 10 ) % 9);
  •  
  • // Return the random letter string we get from the
  • // array of letters above.
  • return( "[" + arrLetters[ intLetter ] + "]" );
  • }

Try calling the function on its own a few times, just to see how it behaves.

 Launch code in new window » Download code as text file »

  • alert(
  • RandomString() + "\n" + RandomString() + "\n" +
  • RandomString() + "\n" + RandomString() + "\n" +
  • RandomString() + "\n" + RandomString() + "\n" +
  • RandomString() + "\n" + RandomString() + "\n"
  • );

As you can see, it randomly (as random as possible) picks a letter to return. Now, let's call the replace with the RandomString() method sent as the second argument. We will do this a few times so you can see the randomness in effect.

 Launch code in new window » Download code as text file »

  • alert( strText.replace( "th", RandomString ) );
  • alert( strText.replace( "th", RandomString ) );
  • alert( strText.replace( "th", RandomString ) );

Notice that we are passing in a POINTER to the function but not actually calling it. RandomString vs. RandomString(). There's one thing I did not mention yet. Not only can you pass in a function as an argument, but when the replace method is taking place, it passes in the target match as an argument to this function. We could have re-written the function as such:

 Launch code in new window » Download code as text file »

  • function RandomString2(
  • strTargetInstance // This is the target string match instance.
  • ){
  • var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
  • var intLetter = (Math.floor( Math.random() * 10 ) % 9);
  •  
  • // Return the random letter string we get from the
  • // array of letters above. This time, though, we are
  • // going to include the target string to demonstrate
  • // that it has been passed in.
  • return( "[" + strTargetInstance + " : " + arrLetters[ intLetter ] + "]" );
  • }

Now, we will run it again, just once, so you can see it in action.

 Launch code in new window » Download code as text file »

  • alert( strText.replace( "th", RandomString2 ) );

Notice now that the replace string is the form of [th : X]. That is pretty cool, but it gets even cooler. This same methodology applies to doing replacements using regular expressions (didn't you have a hunch we'd see them again).

Just to kick of this demo, I will run the global regular expression replace to show that it works the same way.

 Launch code in new window » Download code as text file »

  • alert( strText.replace( new RegExp( "th", "gi" ), RandomString ) );

Notice that we have now replaced all [g] the case insensitive [i] substring matches with the random letter.

This is very cool, but regular expressions take this even one step further. You can group parts of a regular expression and each group will get passed as an argument to the function method. In this example, let's group each letter and have them passed as an argument.

 Launch code in new window » Download code as text file »

  • function GroupReplace(
  • strMatchingString, // The entire string matched.
  • strFirstLetter,    // First group from RegExp.
  • strSecondLetter    // Second group from RegExp.
  • ){
  • // Instead of doing any random letter stuff like the
  • // previous examples, we will just place brackets
  • // around each of the groups to demonstrate the
  • // regular expression grouping.
  • return( "[" + strFirstLetter + "][" + strSecondLetter + "]" );
  • }

The one caveat here, that is different from the standard string replace method is that when using regular expressions, the first argument passed into the function, like the string replace, is the entire matching string.

Now, let's run it with groups in the regular expression. Groups are denoted by () around parts of the expression. Let's run a global, case insensitive match for a maximum amount of fun :)

 Launch code in new window » Download code as text file »

  • alert(
  • strText.replace( new RegExp( "(t)(h)", "gi" ), GroupReplace )
  • )

Notice that all the instances of "th" were replaced with the case-appropriate "[t][h]"

So now that we have seen the technicals of the Javascript string replace method, let's explore some ways that we can leverage the replace method to do non-replace actions. For example, we can use the Javascript string replace method to COUNT the number of times a string appears in the given string.

 Launch code in new window » Download code as text file »

  • // This counts the number of times a string matching the
  • // given regular expression can be found in the given text.
  • function CountValue( strText, reTargetString ){
  • var intCount = 0;
  •  
  • // Use replace to globally iterate over the matching
  • // strings.
  • strText.replace(
  • reTargetString,
  •  
  • // This function will get called for each match
  • // of the regular expression.
  • function(){
  • intCount++;
  • }
  • );
  •  
  • // Return the updated count variable.
  • return( intCount );
  • }

Alert the count of the reg expression.

 Launch code in new window » Download code as text file »

  • alert(
  • "Value Count: " +
  • CountValue( strText, new RegExp( "th", "gi" ) )
  • );

You might be confused by the nested functions in the example above. Since the function being passed to the replace method is a nested function, Javascript will search the local variable scope for "intCount." When it cannot find it, it will move up the scope chain to the CountValue() function which does contain a variable intCount. This is the variable that will be updated for each iteration of the loop.

One last example that seems to stump a lot of people is the replacing of strings that span multiple lines. In our sample text, the line break "\n" is what creates several lines that we can try to match across. The trick is just to treat the "\n" as just another character.

For this example, we will replace the character "s" that ends a word, followed by any white space, until the end of the next word.

 Launch code in new window » Download code as text file »

  • alert(
  • strText.replace( new RegExp( "s\\b[^ ]+", "gi" ), "[X]" )
  • );

As you can see, the matches were made across the line break with no problem at all. By treating the "\n" as just another character that might come up and be matched on, there is no problems to worry about. In our example, the clause "[^ ]" will match on any character that is NOT a space character. This includes alpha-numeric characters, punctuation, and even the new line character.

One caveat to remember is that while in ColdFusion, new lines that come out of a textarea are represented by the character 13 followed by 10, once inside a Javascript string, the new line is JUST "\n".

Well, that's the short and skinny of Javascript String replacement tips and tricks. I am sure you are beginning to see just how crazy awesome they can be. And, if you don't know your regular expressions, I hope that this little tutorial has piqued your interests. They will change your life.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page





Reader Comments

Aug 23, 2006 at 12:28 AM // reply »
1 Comments

There are a LOT of scripts out there that use replace() assuming it'll do a global replace without using a regex (and yes, they're all broken). Nice to find a full and detailed description, thanks :).


Aug 23, 2006 at 3:21 PM // reply »
74 Comments

No problem my man, always glad to help. Javascript rules, and RegExp is wicked sweet.


Marieke
Oct 4, 2006 at 8:59 AM // reply »
1 Comments

try this , for replacing more than one charachter

<script>
test="kuut";
test = test.replace(/u/g, 'a' );
alert(test);
</script>

or for \n:

var test = text.replace(/\n/g, '<br>');


Toan Nguyen
Oct 20, 2006 at 5:50 PM // reply »
2 Comments

I just want to thank you for your article on string replacement methods. It was just so cool. Thanks a million times.


Toan Nguyen
Oct 20, 2006 at 6:02 PM // reply »
2 Comments

How about an option to replace whole words only? Thanks.


Oct 20, 2006 at 6:15 PM // reply »
6,371 Comments

Toan,

Glad to help! Javascript is an awesome, powerful language. Getting whole words is a bit of sticky matter. You can't quite use the word boundry "\b" because that won't match on punctuation. For instance, in the word "can't", the expression \b\w+\b would match "can" since "'" is a non-word character.

If you know the set of data you have conforms to a certain format (ie. NOT having punctuation, then you can use the \b (and I think \A and \Z). If you are gonna use punctuation, things just get harder.

Hope that helps a bit and not confuses you more.


Dec 15, 2006 at 9:35 AM // reply »
1 Comments

Stumbled across your site searching Google. Great examples. I really liked the example of extending the String object to make the replaceAll method available globally. There is one change I would make which is to do a quick check to insure you don't get caught in an endless loop:

if(strTarget != strSubString) {
while loop etc...
}


Dec 15, 2006 at 1:07 PM // reply »
6,371 Comments

Jared,

Thanks for enjoying the site and the examples. I am not sure how you would get caught in an endless loop. However, nothing wrong with checking for equality right up front so that you don't have to do any extra parsing.


GEV
Dec 26, 2006 at 10:16 PM // reply »
1 Comments

split.join works much more predictable.


Rajakuamr
Jan 11, 2007 at 1:41 AM // reply »
3 Comments

::cool work::


Rajakuamr
Jan 11, 2007 at 1:41 AM // reply »
3 Comments

::cool work::


Rajakuamr
Jan 11, 2007 at 1:47 AM // reply »
3 Comments

::cool work::


Peter
Jan 12, 2007 at 8:38 AM // reply »
1 Comments

great article...i was just wondering how you would do a replace with a regex for "(h)"

how would you define a regex replacing the exact match of those 3 characters with say [X]?

so yesyeyses(h)sdgfsd(h)

would become:

so yesyeyses[X]sdgfsd[X]

thx!


Mar 6, 2007 at 7:16 AM // reply »
1 Comments

wow , great guide


Mar 15, 2007 at 11:23 AM // reply »
2 Comments

my FF javascript console says:
replaceAll is not a function


Mar 15, 2007 at 11:26 AM // reply »
2 Comments

oh, I see, the other script should be included.

thanks!


bons
Mar 23, 2007 at 10:20 PM // reply »
1 Comments

can you use this to replace an image? For example, I am using a 3rd party host software that allows some customizations but none directly to the code. It does let you insert your own header code to add to your pages. The software uses a default image that I want to replace with my own default image and I'm wondering if I can do that using a variation of this javascript. So basically I'd want to replace any instances of www.theirsite.com/theirimage.jpg with www.mysite.com/myimage.jpg.

Possible?


Mar 23, 2007 at 11:26 PM // reply »
6,371 Comments

@Bons,

You can certainly do something like that. I have not tested this, but something like:

for (var i = 0 ; i < document.images.length ; i++){

if (document.images[ i ].src.match( new RegExp( "www\.theirsite\.com/theirimage\.jpg', "i" ))){

document.images[ i ].src = document.images[ i ].src = "www.mysite.com/myimage.jpg";

}

This actually would not really call for a RegEx. But, depending on your rules, it might.


someone
Apr 28, 2007 at 10:39 AM // reply »
1 Comments

there's no need to create a RegExp object inside replace function, as the latter supports regular expressions itself, e.g.:

str.replace(/<br>/gi,"\n");

where gi obviously stends for global search + case insensitive.

same applies for match(), search() and the like.


Apr 28, 2007 at 12:19 PM // reply »
6,371 Comments

While that is true, I find it much less readable. Using new RegExp() allows me to slightly break up the code and let me read it more easily. It just personal.


Jul 17, 2007 at 4:06 PM // reply »
1 Comments

It was nice article I have read on javascript. The presentation was wonderful. It was quite useful for me and it also showed the power of regular expression in javascript.

Thanks.


Teresa
Aug 22, 2007 at 11:49 AM // reply »
1 Comments

THANK YOU! FINALLY someone who can explain things clearly and simply....


Aug 22, 2007 at 12:31 PM // reply »
6,371 Comments

@Teresa,

Glad to help. If you ever get stumped on something and want a demo / tutorial / explanation, just let me know.


Becks
Aug 27, 2007 at 4:25 AM // reply »
2 Comments

Hi Ben,

This was a true lesson in string manipulation for me, so thumbs up on this article.

My question is how would I escape single or double quotes with your first example? For example, given the text:

"Jane's Defense Weekly"

I ended up looping endlessly by trying to replace "'" with "\'"; or I clearly don't understand how to escape quotes. I suspect there's probably a more elegant way of doing with with RegExp but you know better than me :)


Aug 27, 2007 at 7:28 AM // reply »
6,371 Comments

@Becks,

I am not sure what you mean. You shouldn't have to escape a single or double quote unless they are breaking the way you write the text in the first place. Escaping a quote doesn't actually change the character, it just tells the Javascript parsing engine NOT to end the current string but rather to treat the escaped quote as a character literal within the string value.

What are you trying to do?


becks
Aug 28, 2007 at 11:55 AM // reply »
2 Comments

Sorry if my question was vague, I'm using Ajax to send queries to an Oracle database.

The problem I was having was that for Oracle strings containing the single quote (') need to have it escaped. So I know typically you'd ensure that the value you send to the database is something like this:

"Jane\'s Defense Weekly"

This way you don't get an SQL error. With your first example I found that I was going into an endless look because I was using the wrong syntax. Using the RegExp example, I solved my problem.

I also found out for oracle single quotes are escape with another single quote and not the slash like in JavaScript or Java strings.


Aug 28, 2007 at 12:11 PM // reply »
6,371 Comments

Ahh, ok cool. Glad you got it working.


Oct 13, 2007 at 9:11 PM // reply »
2 Comments

Great article, how can you replace two different characters in the one expression for example if it finds < replace with < if it finds > replace with >?


Oct 13, 2007 at 9:13 PM // reply »
2 Comments

Sorry in my last post it was supposed to show the html character set for less than and greater than (& lt; & & gt;)


Oct 15, 2007 at 8:01 AM // reply »
6,371 Comments

@Ryan,

All you would need to do is match on both those characters and then replace them in the given function. Something like this:

your_text.replace(
... new RegExp( "(<|>)", "gi" ),
... function( $0, $1 ){
...... if ( $1 == ">" ){
......... return( "& gt;" );
...... } else {
......... return( "& lt;" );
...... }
... }
);

Clearly, you wouldn't use periods, but you get the point I hope.


Nikolaus
Nov 25, 2007 at 9:57 AM // reply »
2 Comments

Hi Ben,
the String.prototype.replaceAll variant is definitely the most elegant. I have just one litte improvement in mind:

it runs into an endless look when given identical parameters (can occur when used dynamically on data). i.e. a little

<code>if(strTarget == strSubString) return;</code>

would be helpful


Nov 25, 2007 at 4:17 PM // reply »
6,371 Comments

@Nikolaus,

It shouldn't be endless because, in theory, the next match should be searched for after the point of the last match. So, even if you were to replace the existing match with itself, the matching engine should continue on with the rest of the string.

However, that is just my theory. I will check to see if that is a reality.


Kamal
Jan 18, 2008 at 9:32 AM // reply »
1 Comments

Very helpful. Thanks for the post.
Here is the code which will replaces all double quote into escape sequence.

sStrValue = sStrValue.replace( new RegExp('(")', "gi" ),
function( $0, $1 )
{
if ( $1 == '"' )
{
return( '"' );
}
});


Jan 20, 2008 at 10:22 AM // reply »
6,371 Comments

@Kamal,

I am not sure I am following what your code will do. I don't think you need the anonymous function; your regular expression does not have any optional patterns and there is not special logic in the sub function. Meaning, if the pattern is matched, your conditional if() statement will *not* be true.


calicoder
Jul 25, 2008 at 8:29 PM // reply »
2 Comments

Your replaceAll code is *** NOT SAFE ***

You should be using javascript's regular expression support for this instead of a loop:

stringValue.replace(/something/g, "something else");

Your solution causes infinite loop. Example:

stringValue.replaceAll("&", "&");

In this scenario you'd like to replace all special characters of an XML element body.


calicoder
Jul 25, 2008 at 8:32 PM // reply »
2 Comments

previous post should be

stringValue.replaceAll("&", "& amp;");

** no space **


Jul 28, 2008 at 9:56 AM // reply »
6,371 Comments

@Calicoder,

There can definitely be some complications. I know that with the Javascript "Exec" command( String.exec() ), I have run into some endless processing loops. You just have to be carefule about how you replace and how you define the flags (if I remember correctly, the lack of the global flag, "g", messed me up in the exec() experiment). Of course, all of these things should be ironed out in development, pre-production.


blueprints
Sep 10, 2008 at 12:25 PM // reply »
4 Comments

Hello Ben,

How can one write a javascript string replace
which changes these examples:

Example 1:
C:\WINDOWS\system32\cmd.exe
to:
file:///C|/WINDOWS/system32/cmd.exe

Example 2:
file:///C|/WINDOWS/system32/cmd.exe
to:
C:\WINDOWS\system32\cmd.exe

Is it possible to use javascript replace method with the
<input> tag? Here is a mock up of what I mean:
<input type="text" size="40" value="file:///C|"><button>convert1</button>
<br />
<br />
<input type="text" size="40" value="C:\"><button>convert2</button>

tia,
blueprints


nikolaus
Sep 10, 2008 at 1:00 PM // reply »
2 Comments

To blueprints:

Here are your javascript expressions to convert a Windows file path to a UNC path and back:

Example 1:
Var inputstring = ... (do that yourself)(grab string from the input node via the usual dom access methods - use a js toolkit if you find it hard to get it to run on all browsers)

Var result = "file:///" + inputstring.replace(/\:/, "|").replace(/\\/g, "/");

Example 2 is a little harder:

var inputstring = ...
...
var result = /file\:\/\/\/(\S+)/.exec(inputstring)[1].replace(/\//g, "\\").replace(/\|/, ":");

Greets and good luck.


blueprints
Sep 11, 2008 at 11:48 PM // reply »
4 Comments

<html>
<head>
<title>Path Replace</title>
<script type="text/javascript">
<!--
function regexpDemo(monkey,testNum) {
switch (testNum) {

case 5:
monkey.value = monkey.value.replace(/file:\/\/\/C\|/gi,"C:").replace(new RegExp(/\//gi),"\\");
break;

case 6:
monkey.value = monkey.value.replace(/C:/gi,"file:///C|").replace(new RegExp(/\\/gi),"/");
break;
default:
break;
}
}
// -->
</script>
</head>
<body>

<form id="demo5" action="#" onsubmit="regexpDemo(this.monkey,5);return false">
<div><input name="monkey" type="text" size="50" value="file:///C|/WINDOWS/system32/cmd.exe" />
<input type="submit" value="C:\" class="buttonHi" style="width:60px;" />
<input type="reset" value="Reset" class="buttonHi" style="width:60px;" /></div>
</form>

<form id="demo6" action="#" onsubmit="regexpDemo(this.monkey,6);return false">
<div><input name="monkey" type="text" size="50" value="C:\WINDOWS\system32\cmd.exe" />
<input type="submit" value="file:///C|" class="buttonHi" style="width:60px;" />
<input type="reset" value="Reset" class="buttonHi" style="width:60px;" /></div>
</form>

</body>
</html>

Thanks Ben.

Regards,
blueprints


blueprints
Sep 12, 2008 at 12:24 AM // reply »
4 Comments

Ben,

It occurs to me I should try for a "Short" path while I am at it.
Is there a way to use Javascript String Replace Method to get:

C:\PROGRA~1\INTERN~1\iexplore.exe

rather than the Windows file path or UNC?
C:\Program Files\Internet Explorer\iexplore.exe
file:///C|/Program Files/Internet Explorer/iexplore.exe

8.3
blueprints


Sep 12, 2008 at 8:16 AM // reply »
6,371 Comments

@BluePrints,

regular expression in the Javascript String replacement method are all about patterns. If you can find the pattern, you can make it happen. So, what is the pattern here:

1. We have a "list" of path items separated by back slashes.
2. Each of those list items has to be converted to something that is 8 characters (or less).


blueprints
Sep 12, 2008 at 1:02 PM // reply »
4 Comments

Ben,

C:\Program Files\Internet Explorer\iexplore.exe
C:\PROGRA~1\INTERN~1\iexplore.exe
C:\123456~8\123456~8\iexplore.exe
C:\(leave 6 characters alone)(replace the rest of the characters up to the next backslash with "~1")(then the backslash)(repeat the leave 6 characters alone)(replace the rest of the characters up to the next backslash with "~1")(then the backslash)(repeat the leave 6 characters alone)(replace the rest of the characters up to the next backslash IF their is another backslash with "~1")

The pattern always seems to be to REMOVE the characters after the 8 characters up to the next backward slash minus 2 plus ~1 and REPEAT the pattern for X number of directory folders.

C:\Program Files\Internet Explorer\abcdefghijklmnopqrstuvwxyz.txt
C:\PROGRA~1\INTERN~1\ABCDEF~1.TXT

Also, I do not believe the changing to uppercase is necessary or even desired. If i recall from the DOS days (the good old days) the capital uppercase was not necessary. I am getting these paths using the Ninotech right click PathCopy and maybe the uppercase characters are just a peculiarity of Ninotech. I do not know enough to say either way. These previous C:\ and the file:///C| string replaces are my first attempts at regex or string replacement, and regarding the above patterns and trying to analyze a discernable pattern - i am just not educated nor expert enough to figure out how to express them using the replace method. Neophyte. User. Amateur. I don't think i even qualify as geek or hack. Anyway I do not yet have the pieces to the puzzle for this Short Path Javascript String Replace, and without the pieces i am lost.

Regards and real thanks Ben,
blueprints


Schalk Versteeg
Nov 21, 2008 at 8:33 AM // reply »
1 Comments

Thanks a lot, it helped me a lot in understanding regular expressions better.

@blueprints
~1 can become ~2 (etc.) if 2 (or more) folder/file names do have the same first 6 characters and is in the same sub folder.
(It works in Alphanumerical order).
ex.
\Program Files\ -> \Progra~1\
\Programa and tests\ -> \Progra~2\
\Programs et al\ -> \Progra~3\


Jan 30, 2009 at 4:27 AM // reply »
1 Comments

very nice page indeed. i am visiting your other pages too. regards.


Magmatrix
Feb 28, 2009 at 11:27 AM // reply »
1 Comments

Please note that you have a race condition if you do something like:

s="my string with % percent in it";
s.replaceAll("%","%20"); // URL encoding example

Any "%" will be replaced with "%20", which will then be replaced with "%%20", then "%%%20" and so, using 100% cpu, eating memory until your browser finally crashes (or something equally nasty).

The fix is simple:
the second "indexOf(strTarget)" should be changed to:
"indexOf(strTarget,intIndexOfMatch+length(strSubstring))"

/M


Mar 2, 2009 at 11:37 AM // reply »
6,371 Comments

@Magmatrix,

If you use a regular expression with a "g" (global) flag, I don't think you will run into this - it should be smart enough to know where the end of the last match was and to run from there.

Using a standard string replace might not have that kind of built-in ability.


Samitha
Mar 19, 2009 at 7:25 AM // reply »
1 Comments

Excellent ... You Save my time..Tahnks a lot.!


Will
Apr 4, 2009 at 7:28 AM // reply »
1 Comments

I've seen the light! At 4:30am! thank you!


Khoa
Apr 28, 2009 at 2:49 PM // reply »
1 Comments

I was pulling my hairs because the JS replace() replaces only the 1st instance ... doesn't replace all like in C#. Ben, thank you for this shared information!


Apr 28, 2009 at 3:01 PM // reply »
6,371 Comments

@Khoa,

If you use the "global" flag in the new RegExp() constructor, it should replace all instances:

new RegExp( "xyz", "g" )


May 18, 2009 at 7:17 PM // reply »
1 Comments

So what, does that mean you're not going to fix it? Nice

PS I included my email this time because I know you're just going to delete this comment too.


May 18, 2009 at 7:26 PM // reply »
6,371 Comments

@Some Guy,

The issue has just been fixed. I finally downloaded the Beta of Chrome. It looks like their is a discrepancy in the way that the Chrome Beta returned the height() value in the jQuery library. It was always 6px smaller than innerHeight / scrollHeight, which is why it kept growing.

In the future, feel free to post your *real* information as that is quite welcome 'round these parts.


Albert
Jun 11, 2009 at 4:35 PM // reply »
2 Comments

Interesting coding, I'll look more into it. Thanks for the sample.


Jul 14, 2009 at 5:19 AM // reply »
2 Comments

Hi! what do you think about this:

String.prototype.replaceAll = function(strTarget, strSubString){
return this.split(strTarget).join(strSubString);
}

i'd use it for strings only, not for regex.

WBR,
Vovka


Doug
Jul 16, 2009 at 8:57 AM // reply »
1 Comments

Very consise, thanks!

Doug


Jul 18, 2009 at 3:54 PM // reply »
6,371 Comments

@Vladimir,

Very cool idea. I believe the Split() method can actually take either a string OR a regular expression, so this would work either way. Slick!


Aug 3, 2009 at 4:53 AM // reply »
1 Comments

Your ideas are great, but i am not able to grasp these fully. pls make tutorials from scrathc.


Aug 5, 2009 at 9:16 AM // reply »
6,371 Comments

@Arti,

I am not sure what you mean "from scratch". Is there something here that I am not explaining well?


Sathish
Aug 7, 2009 at 9:28 AM // reply »
2 Comments

Hi,

I hope the following simple code also does the same(replace's all occurences of substring),

str = str.replace("find","replace")//this will replace the first occurence.

To ReplaceAll you have to do it a little differently. To replace all occurrences in the string, use the g modifier like this:

str = str.replace(/find/g,"replace")

Regards,
Sathish.


Vladimir
Aug 7, 2009 at 9:37 AM // reply »
2 Comments

@Sathish,


simply brilliant :)


Sathish
Aug 11, 2009 at 4:40 AM // reply »
2 Comments

@Vladimir thanks :-)


Pasha
Aug 29, 2009 at 2:18 AM // reply »
1 Comments

Many thanks to the author! :)


Zigo
Oct 7, 2009 at 5:49 AM // reply »
1 Comments

Hi,

I tried using regular expression and trying to pass a variable for the replace string

var rep = 'x';
mystring = mystring.replace(/rep/gi,'y');

How do I tell the replace function that rep is actually a variable and it should use its value


Nov 1, 2009 at 3:43 PM // reply »
6,371 Comments

@Zigo,

I think in that case, you will have to use the explicit RegExp constructor:

new RegExp( rep, "gi" )


Nov 7, 2009 at 5:53 PM // reply »
3 Comments

You can find here an advanced function that prepared with javascript replace function. This can make the first letters of words, sentences, lines and whatever you define automatically:

http://www.memiso.com/uppercasing-first-letters-of-words-sentences-or-lines-in-java.html


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 7, 2009 at 5:53 PM
Ask Ben: Javascript String Replace Method
You can find here an advanced function that prepared with javascript replace function. This can make the first letters of words, sentences, lines and whatever you define automatically: http://www.m ... read »
Andrew Neely
Nov 7, 2009 at 4:56 PM
A Moment That Touched Me - The Fountainhead
Ben, Glad you enjoyed the podcast. Yeah, the Tank Riot guys can get really chatty during the episodes, but that's part of the charm of it for me. They've covered everything from Nichola Tesla to Cha ... read »
Nov 7, 2009 at 4:43 PM
Building A Fixed-Position Bottom Menu Bar (ala FaceBook)
Is it possible to make some more MenĂ¼`s ? ... read »
Jill
Nov 7, 2009 at 11:40 AM
How To Unformat Your Code (Like A Pro)
Derek, I think you might be right - sweet! Thanks for the link :) ... read »
Nov 7, 2009 at 11:25 AM
How To Unformat Your Code (Like A Pro)
I think it would be way easier to just use this http://www.logichammer.com/html-formatter/ He just released v3 and it rocks. ... read »
Jill
Nov 7, 2009 at 7:58 AM
How To Unformat Your Code (Like A Pro)
LMAO - this was pretty funny! I have to admit - I also love to reformat code so I can read it. My boss used to tell me to leave my OCD at home. Now I don't feel so bad after reading everyone else' ... read »
Nov 6, 2009 at 10:10 PM
How To Unformat Your Code (Like A Pro)
The timing of this post is just uncanny. I spent the last 15-20 minutes manually un-formatting my "Ben Nadel" style code within a CFC of mine. I was really digging the readability a few weeks ago, bu ... read »
Roe
Nov 6, 2009 at 5:11 PM
Passing Arrays By Reference In ColdFusion - SWEEET!
ArraySort also reorders the results of these java obj's ... read »