JavaScript

JavaScript – String Replace

I should not let this pass by. I am recently playing with some JavaScript string manipulation, especially the string replace. All I want is a simple string operation that will replace all occurrences of a certain piece of string contain in a string.

For example if I have a string:

I saw, I came, I conquer.

I want to replace all occurrences of “I” into “You”, which would yield this result.

You saw, You Came, You conquer.

My actual problem is that I have a link (anchor tag) which has an inner HTML of a string enclosed with a series of “ ”. I put that space to increase the clickable area of the link. Then I need to strip that spaces to get the exact value / content of the anchor tag.

Sample:   1b  
When stripped, it should be: 1b

So here is the JavaScript code:

var text = //get the link inner HTML
text = text.replace(/ /g, "");

alert(text);

The g parameter means global search. If not specified, only the first occurrence of the string is replace. To search all matching strings, use g parameter. To perform case-insensitive search, use i parameter.

2 thoughts on “JavaScript – String Replace”

  1. di ko naintindihan pero mukhang mahalaga nga sya. these are the stuffs usually unknown to some bloggers like me but is indispensible. thanks to all the genius behind programming.ΓΌ

    salamat din sa pagdalaw!

  2. Lol! Ni-add kita sa aking Google Reader bro utoy, para hindi ko na kelangan mag visit sa site mo just to read your entries. Pero siyempre, kelangan din ako magbasa ng mga comments kaya visit pa rin. πŸ™‚

    Regarding naman sa post na ito, simple lang naman yan, pero importante as part of the basics. Alam mo naman, kung anong natutulklasan ko, i-post ko agad, either sa FriendFeed, Twitter or kung mahaba, sa blog na ito.

    Good luck para sa mga next post mo bro utoy!

Leave a reply

Your email address will not be published. Required fields are marked *