Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at the New York ColdFusion User Group (Mar. 2008) with:

Ask Ben: Javascript String Replace Method

By Ben Nadel on

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.

  • 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.

  • 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.

  • 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.

  • // 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.

  • 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.

  • // 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.

  • // 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.

  • 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:

  • 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.

  • 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.

  • 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.

  • 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:

  • 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.

  • 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.

  • 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.

  • 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 :)

  • 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.

  • // 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.

  • 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.

  • 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.

Tweet This Interesting post by @BenNadel - Ask Ben: Javascript String Replace Method Thanks my man — you rock the party that rocks the body!



Reader 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 :).

Reply to this Comment

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>');

Reply to this Comment

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

Reply to this Comment

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.

Reply to this Comment

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...
}

Reply to this Comment

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.

Reply to this Comment

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!

Reply to this Comment

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?

Reply to this Comment

@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.

Reply to this Comment

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.

Reply to this Comment

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.

Reply to this Comment

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.

Reply to this Comment

@Teresa,

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

Reply to this Comment

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 :)

Reply to this Comment

@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?

Reply to this Comment

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.

Reply to this Comment

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 >?

Reply to this Comment

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

Reply to this Comment

@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.

Reply to this Comment

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

Reply to this Comment

@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.

Reply to this Comment

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( '"' );
}
});

Reply to this Comment

@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.

Reply to this Comment

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.

Reply to this Comment

@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.

Reply to this Comment

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

Reply to this Comment

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.

Reply to this Comment

<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

Reply to this Comment

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

Reply to this Comment

@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).

Reply to this Comment

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

Reply to this Comment

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\

Reply to this Comment

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

Reply to this Comment

@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.

Reply to this Comment

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!

Reply to this Comment

@Khoa,

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

new RegExp( "xyz", "g" )

Reply to this Comment

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.

Reply to this Comment

@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.

Reply to this Comment

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

Reply to this Comment

@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!

Reply to this Comment

@Arti,

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

Reply to this Comment

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.

Reply to this Comment

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

Reply to this Comment

@Zigo,

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

new RegExp( rep, "gi" )

Reply to this Comment

what if i wanted to replace just one word/letter but not the first. say i want to replace the second "a" in this string but not the first?
" hiya hiya "
is it posible? if so please inform me i am working on a project that absolutely requires this.

Reply to this Comment

first, I would like to say thank you so much for the article. but I still can't solve a problem related with this topic.

var myString="This is my liv3 return";
var pattern=li;
var result=myString.replace(pattern + /(\d)3/, live);

my goal is, how to put the pattern in user input.
correct me if i'm wrong.

I will appreciate all your comment
Thanks,

Regards,
Mardi

Reply to this Comment

@Mardi,

You can't combine a string with an implicit regular expression pattern. You have to them both as strings:

var result = myString.replace(
new RegExp( pattern + "\\d3", "" ),
"live"
);

Here, both "pattern" and the \d3 are strings and can therefore be concatenated. Of course, as a string, you have to worry about special characters in the pattern (such as escaping the back slash).

Reply to this Comment

I declare a gobal variable. Later I update that with a string. Within that string are placeholders. I determine what the correct words are for each placeholders within an if { statement and use a replace command to update the placeholder }. when I go to the next placeholder and do the replace command the gobal string does not contain the last replace data. I can replace individual items but how do you update and keep the items from replace to repalce?

Reply to this Comment

@Bruce,

String in Javascript are immutable. That means you cannot change them once they are set. As such, when you attempt to modify them, what actually happens is that your result is an *entirely new* string, not a modified one.

Because of this, you have to be sure to re-store the new string into the old variable. For example:

var a = "something";
a = a.replace( "e", "_" );

Notice that I am not just calling replace() on the string - I'm also storing that return value (returned from the replace() method) *back* into the variable, "a". In this way, you will keep the replacements.

Reply to this Comment

I am new to regexp and have spent some time trying to come up with an expression that changes a single-quote that isn't inside a double-quote to a "#". I finally got really close, even though I don't really understand how it is working. The part I need help on is getting it to work when the very first character of the string is a single-quote. A minor problem is that once it finds the single-quote to change, it changes all of them from that point on. Here is what I have:

Test 1 (almost works except for last single-quote change):
strtxt: a = "123abc's" or c="xyz's" then ' yy ' yy
regexp: (([^\S"])|(^.*('|([Rr][Ee][Mm]))))('|([Rr][Ee][Mm]))[^.*]
replacechar: rem

result: a = "123abc's" or c="xyz's" then rem yy rem yy

Test 2 (only works if the single-quote is not the first character--if you put a space in front of the single-quote, it works):
strtxt: ' "yy " '
regexp: (([^\S"])|(^.*('|([Rr][Ee][Mm]))))('|([Rr][Ee][Mm]))[^.*]
replacechar: rem

result: ' "yy " ' (fails when single-quote first character so nothing changes)

Any help or teaching moment would be appreciated. These are tough to understand because I can't see how the whole thing works at each step. I've read a lot to get where I am, but there is a lot for me to learn.

Reply to this Comment

Hi,

Am new in the JS, I have developed one XSL for viewing purpose in xml file, I want know how to assign the xml text in "var" value. Within the XSL file (i.e. text())

Actual in my requirement is particular word in XML file (i.e. this word anywhere appears in the xml element) need to change another one word (e.g "Ganesh" to "Selva"). Also how to handle the special character (quotes, apos, plus, minis, etc...)

Thanks,
Selva

Reply to this Comment

Hi,

I would need to replace 12 out of 16 characters of a numerical string with a special character.
tried with the following but it didnt work.

string.replace(/^([0-9]+)([0-9]{4})$/g,'$')

can some help me on this

Reply to this Comment

@Ban,Are the numbers to be replaced always in the same position with in the string? If so you can use substr to get the numbers to keep and join that to the characters you want "changed".

Reply to this Comment

@bruce, i agree with you on that..

In the option prescribed by you i tried to loop through the characters which i want to replace with special character..

but in that case am getting some js error.

var tempstring="";
for (var i = 0; i < data.length; i++)
{

tempstring =tempstring + "*";

}

Reply to this Comment

@Wize,

That's a really tough pattern to have to figure out - at least for me. I'll have to give that some thought. I don't often deal with "Except" type cases in patterns.

@Selva,

I have not done XSL with Javascript before; I am sorry, but I wouldn't even know where to tell you to start.

@Ban,

I am a little bit confused as to what you are trying to do. Are you just trying to replace the first 12 characters of a string with 12 "*"?

Reply to this Comment

If this is what you're looking for, this is what it does:

string.replace(/[0-9]/g,'$')

Replace all numerics in the string with '$'. So 11223 would be replaced with $$$$$.

I believe your initial string, string.replace(/^([0-9]+)([0-9]{4})$/g,'$'), looked for 1 or more numbers (which it can only get 1 numeric because the next match is numeric) followed by 4 numbers to match. That means something like 11223 would match and be replaced with a single $ because the match is on 11223 not 1, then 1, then 2, then 2, then 3.

Reply to this Comment

@Wize, the details of what you're trying to do are not clear to me. E.g., what's the deal with matching "rem" case insensitively (are you trying to harmonize the casing?) and do you only want to replace the first single quote (that is not enclosed in double quotes) on each line?

Anyway, what you're trying to do is not possible using a single regex in JavaScript (since there's no lookbehind, etc.) unless you use a replacement function. E.g.:

<pre><code>
var result = str.replace(/"[^"]*"|(')/g, function ($0, $1) {
return $1 ? "rem" : $0;
});
</code></pre>

If this isn't quite what you're trying to do, it's probably easy to adjust to fit your requirements if you explain them more clearly.

Reply to this Comment

@Wize,@Ben

Here is my requirement...

i would need to have the data in the form of
$$$$$$$$$$$$$$$$1234
i.e i would need to replace all the numbers except last 4.(in total 16 numbers)..

Thanks in advance

Reply to this Comment

One way to replace the first 12 digits of 16 is like this:

string.replace(/\d{12}/, '$$$$$$$$$$$$$$$$$$$$$$$$')

This will replace:
1234567890123456

with:
$$$$$$$$$$$$3456

Since you are using a dollar sign as the replacement character, you need two for every one you will use (so there are 24 $'s.) If you use an asterisk instead, you would only need 12 of them. The $ is a special character because it is used to match parenthesis sets.

string.replace(/\d{12}/,'************')

************3456

Reply to this Comment

@ban

I'm not sure what you mean, but here is a way to show the first 12 and block out the last 4 if that's what you mean.

Here is the number:
1234567890123456

Here is the replacement formula:
string.replace(/(\d{12})(\d{4})/,'$1$$$$$$$$')

Again, remember there are 2 $'s for every $ to output. The $1 matches and returns the first 12 digits, then the 8 $'s replace the last four digits with $'s.

Result:
123456789012$$$$

Reply to this Comment

This should be really simple, but for some reason I'm not getting it. I want to match on "do" but not "doc". It's possible that there could be text after "do", but "do" can also be alone. For my test, I chose to test for it alone and I can't match "do" without matching "doc" too.

I want this to match "do" but not match on "doc".
The text: do
Reg Exp: do[^c]

This doesn't match "do" or "doc" matches "do ", "doa", etc. What I need is to have a "not c" or "end of line". I did try "do[^c|]" hoping that the ^c| would match "not c" or "nothing".

Reply to this Comment

@Wize,

You need a negative look-ahead. Your pattern is trying to match *three* letters, "do", followed by anthing NOT-C. What you really want is to match "do", so long as it is not followed by C.

do(?!c)

(?!c) is a negative look-ahead for C. I am not sure that it is supported in Javascript, but I think it is.

Reply to this Comment

Thank you. That worked. I haven't used the look-ahead feature before and this is just what I needed.

Reply to this Comment

Thanks for the tip.
As pointed out in the comments, you code may produce an infinitive loop.
(always a good idea to add a counter in a while loop and break the code if the counter reach a limit, I think...)

Please find below a simple suggestion that did the trick for me(for the sensitive case anyway):

String.prototype.replaceAll = function(
strTarget, // The substring you want to replace
strSubString // The string you want to replace in.
){
var strText = this;
var res="";
var tab=strText.split(strTarget);

for (var i=0;i<tab.length-1;i++)
tab[i]=tab[i]+strSubString;
for (var i=0;i<tab.length-1;i++)
res+=tab[i];

res+=tab[tab.length-1];

return( res);
}

Regards,
Phil

Reply to this Comment

@Phil,

That's quite clever! I never thought of using the target string as a delimiter in the split() method. Snazzy!

Reply to this Comment

I am trying to make a java program to count the number of times that these punctuation marks occur in a body of text: , : ; . ! - ' " ? / \
I am using this piece to ferret out the commas:
numcommas = inputF.replaceAll("[^,]","").length();. However, following this syntax for the rest of the punctuation marks does not work. Is there a body of reference to handle all punct. marks using replaceAll? i have searched and searched and everything seems so vague. Is there a proper way to extract these punct. marks that is available as a look up or tutor, or could you please provide me with some insight? This has been bugging me for awhile and I want to get replaceAll down.. Thanks

Reply to this Comment

I'm confused a bit by what you are asking, but if had this sentence:

The color, red, is in the style statement; style: red;.

and wanted to remove all or change all of the commas, colons, and semi-colons, my expression would be:

[,:;]

The result would look like this:

The color red is in the style statement style red. I hope that helps.

Reply to this Comment

@Lance,

It's probably the back-slash that's giving you trouble. You have to escape it most likely. Try something like this:

[^,:;.!'"?/\\-]

Also, I put the "-" at the end of the character class.

Of course, if you are inside of a string, you'll probably have to escape the appropriate quotes and back slashes:

"[^,:;.!'\"?/\\\\-]"

Does that help at all?

Reply to this Comment

I want to change all occurrences of "we" to "they" in the sentence below, but I do not want to change anything within double or single quotes. I also want to keep the case that is used. I believe I need to use look ahead, but I haven't used look ahead that much so I'm not sure how to do it. I'm also not sure this can be done. Can someone help me out with this type of logic? Thanks.

--------------------

When we met and we went ahead even though "we wanted to stop," but 'we' didn't quit. "We" tried hard, but they won not We

--------------------

I'd like "we" changed to "they" in the above sentence without changing anything in double or single quotes and keeping the case of what is changed. Below is the sentence I would like this to like this after the replacements.

--------------------

When they met and they went ahead even though "we wanted to stop," but 'we' didn't quit. "We" tried hard, but they won not They

--------------------

*Note: I am using this in JavaScript's regular expressions

Reply to this Comment

This would be a simpler test. Change:

abc Abc "abc" ABC

to:

def Def "abc" DEF

Change "abc" to "def", preserve case, but don't change anything in double quotes. What would be the expression to do that? Thanks.

Reply to this Comment

It's just ridiculous, attempting to add more thanks but there you are. It just has to be done! Thanks for taking the time to present such an excellent article!

Best regards!

Reply to this Comment

@Wize,

That kind of logic actually gets significantly more complicated. For that kind of approach, check out my other blog post and replacing strings that are NOT inside other strings:

http://www.bennadel.com/blog/1861-Ask-Ben-Replacing-A-String-That-Is-Not-Inside-Of-Another-String.htm

That's a ColdFusion-based blog post, but hopefully it will help you.

@Per,

Thank you very much - I really appreciate that kind of positive feedback. It totally made my day.

Reply to this Comment

Hi Ben,
I've searched the web for hours on this one and your blog seems to come the closest. Most examples use literals but I'm missing how to expand them to use variables.

I'm feeding a regex with a series of lines, and a variable search word or phrase. The code below works, except that it replaces both INs.

var line = "a text includes this in it";
var srchtxt = "in";
var re = new RegExp(srchtxt, "gi");
line = line.replace(re,"|" + srchtxt + "|");

I want just the full word, IN, so I'm trying to add "/b" on either side of the variable as follows:

var re = new RegExp("/b"+srchtxt+"/b", "gi");

but now nothing is found.

What am I missing?
Thanks in advance.
Regards,
John

Reply to this Comment

@John,

Try this:

var line = "a text includes this in it";

var srchtxt = "in";

var re = new RegExp("\\b"+srchtxt+"\\b", "gi");

newLine = line.replace(re,"out");

document.write(newLine);

//output: a text includes this out it

Reply to this Comment

Ben,

I don't normally add comments to articles on any site but this was laid out so well I just had to say thanks.

I knew what I wanted to do and you have written this so clearly that within moments of reading I already had the answer and understood it. Thanks so much!

Reply to this Comment

I am verymuch new to java

I need single statement which can help me replace number of chars from a given string

e.g. I need to replace all numbers (0-9) and chars ('a','b','c') from given string (ancbdec019abecebr0321)

to get result

(ndeeer)

Reply to this Comment

@Tom,

What do you need to change the characers to and are you using Java or JavaScript?

Reply to this Comment

in addition to earlier comment, I want to replace those chars with BLANKs ('')

Reply to this Comment

@Tom,

For Java, which is totally unrelated to Javascript (it was poorly named), you would want to use something like the String.replaceAll() method:

  • newString = yourString.replaceAll( "[0-9abc]+", "" )

Reply to this Comment

This article has been great. But how do you remove a + from a string?

I have Cinnamon+Chocolate+Twists and I want Cinnamon Chocolate Twists.

I tried this:
nameProduct[1] = nameProduct[1].replace(/+/g,'');

...to no avail.

Reply to this Comment

@Sterve,

Try this:
nameProduct[1] = nameProduct[1].replace(/\+/g,'');

and if you want a space instead of just removing the +'s try this:

nameProduct[1] = nameProduct[1].replace(/\+/g,' ');

Reply to this Comment

Thanks. Absolutely brilliant. I hope to not use JS very much but if/when I do I shall make certain I look you up first.

Reply to this Comment

Could you help me please?
This method of javascript replace, could change characters or strings just in alerts but the variable stays the same...how we can repleace the variables for example if I need in string livno repleace l into the 1 ->> 1ivno
THANK'S

Reply to this Comment

Hey, i found your site by google, i don't speak very well english, i need this:

"
<span></span>
<script></script>
<xmp>
<script>alert('hola');</script>
</xmp>
</script>
</span>"

convert to :

"
[span][/span]
[script][/script]
<xmp>
<script>alert('hola');</script>
</xmp>
[/script]
[/span]"

only the <> outside the <xmp></xmp> tags have to change...
i can't write regex to do that :S

Reply to this Comment

@Nikolina,

I am sorry, I do not understand your question.

@Kike,

It would probably be easier to just replace all open/close brackets first and then un-replace the XMP ones. For example (pseudo-code):

  • myString
  • .replace( /</g, "[" )
  • .replace( />/g, "]" )
  • .replace( /\[xmp\]/g, "<xmp>" )
  • .replace( /\[/xmp\]/g, "</xmp>" )

You'll be doing some extra replaces - but it will simplify your logic.

Reply to this Comment

@Ben,

Thanks for reponse..
Yes, i understand that, but, i need what is contained between <xmp> </xmp> not be touched

Reply to this Comment

Hi Ben,

I want to ask you that in java script variable have 32000(I read somewhere) char limit. Due to this limitation i am getting problem in my application i making the .net application in which i have used PageMethod and this pagemethod returning me the 82000 char long string but can anything it should be 10000000 so on. Than what should i have to use to get result in javascript onSucess(result) function. Please Help Me....
Example:
function BindPostDiv() {
PageMethods.BindPostInnerDiv(OnsucessPost);
}
function OnsucessPost(result) {
var InnerDivPost = document.getElementById('InnerPostDiv');
InnerDivPost.innerHTML = result;
}

If result is more that 32000 (82321 in my case)
It is showing error.

Please Ben Help Me..........

Reply to this Comment

Suggest article briefly note that while the Microsoft "javascript" (Jscript) .Replace() string-method has 2 parameters, the Mozilla Javascript (Firefox, Netscape) .Replace() string-method can have 3 parameters, whereas the Microsoft (NON-javascript) "script" (VBscript, VB, VC++, C#, F#) Replace() "method" (so called, but shown with non-object syntax) can have up to 6 parameters! -- all these not to be confused with their corresponding RegEx-object .Replace() methods, which work differently, nor with Mozilla XPCOM Replace(), which is very much different.

Ref:

JScript: http://msdn.microsoft.com/en-us/library/t0kbytzc(VS.94).aspx

Javascript: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

VBscript: http://msdn.microsoft.com/en-us/library/238kz954(VS.85,classic).aspx

VB, etc: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.replace.aspx

VBscript RegEx: http://msdn.microsoft.com/en-us/library/k9z80300(VS.85).aspx

VB, etc. RegEx: http://msdn.microsoft.com/en-us/library/xwewhkd1(VS.90).aspx

XPCOM: https://developer.mozilla.org/en/NsAString/Replace

Reply to this Comment

Your replaceAll function has a flaw.

Question:
What happens if you do this?

document.write("x".replaceAll"x", "xyz"));

Answer:
endless loop

Reply to this Comment

What if you want to replace the second instance found, but not the first one?

Reply to this Comment

Try this replaceAll:
http://www.dumpsite.com/replaceAll.php

It is very fast, and it will work for ALL these conditions that many others fail on:

"x".replaceAll("x", "xyz");
xyz

"x".replaceAll("", "xyz");
xyzxxyz

"aA".replaceAll("a", "b", true);
bb

"Hello???".replaceAll("?", "!");
Hello!!!

Let me know if you can break it, or you have something better, but make sure it can pass these 4 tests.

Reply to this Comment

tomy,

if you want to replace a specific instance (2) in a string.

Use this replaceAll function:
http://www.dumpsite.com/replaceAll.php

and then pass it a anonymous function for "str2" with the following wrapper function:

function replaceInstance(str, str1, str2, instance, ignore)
{
var count = 0;

return str.replaceAll(str1, function(s)
{
count++;
if (count == instance)
return str2;
else
return str1;

}, ignore);
}

document.write(replaceInstance("abcabcabc", "abc", "123", 2, true));

Reply to this Comment

<script>
var str=" Hai'Hello";
wnodow.document('str.replaceAll("'","\\\\'"));
alert(str.replaceAll("'","\\\\'"));

</script>

Output
----------

alert box display the single cou

Reply to this Comment

Here is what I'm getting from the following code:

  • var str=" Hai'Hello";
  • document.write(str.replaceAll("'","\\\\'"));
  • alert(str.replaceAll("'","\\\\'"));

Output:
Hai\\'Hello

This is correct.

The point of this function is to perform a replace all using the javascript replace function via a regular expression for speed, and at the same time eliminate the side effects that occur when regular expression special characters are inadvertently present in either the search or replace string.

Using this function you do not have to worry about escaping special characters. All special characters are pre escaped before the replaceAll is preformed.

Reply to this Comment

Hi
I have been meet an error on while replacing the string

In text area we have type with no. of spaces in a sentence. i want to replace wherever the string "X" present i want to replace there string "y" but it is applicable for first one string replacement. i need whatever the string "x" is present to replace the string "y"
I am using the following example:
var name=x[10].replace("%20"," ")

Reply to this Comment

Hi Ben,
thanks for the tips.

i'm not good at js, just wanted to replace a string with another one without creating a "document.write" is it possible?

the result should be :

  • <div id="listing_product">
  • <p>
  • <span>www.nouveaunomdedomaine.com/12543.php</span>
  • </p>
  • <p>
  • <span>www.nouveaunomdedomaine.com/122127.php</span>
  • </p>
  • </div>

thank you

Brian

Reply to this Comment

Hi..

How to 9.999.999 to 9999999?

So far i have this code

var strText = "9.999.999";

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

alert( strReplaceAll );

But the result is: [X][X][X][X][X][X][X]

Thanks for advance

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.