views:

25

answers:

1

So if you have the following string: "$(document).ready(function() {"

There are three open parentheses "("

I know there is the good 'ol string.replace(/(/g, "replacement_string"); way of doing things, but lets just say that doesn't exist for this question.

Now lets say I have a function that does replaces "(" with "?". Is there a way to perform the function once for every "(" in the string?

+1  A: 

you could split the string using

var theStringinQuestion="$(document).ready(function() {";
var strArr=theStringinQuestion.split("(");

and then run the resultant array through a for in loop like so:

var resultStr="";

for(substr in strArr){
  if(someCondition){ // where someCondition is your condition
    resultStr+=substr+"?"; 
  }else{
    resultStr+=substr+"("
  }
}
pǝlɐɥʞ
I get what you mean by your code and I believe I can make it work in a way that isn't terribly inefficient (I had a while loop method that basically froze my computer for about 2 minutes while performing the operation), but in the for in loop, substr would be the keys of the array, i.e. doing for (substr in strArr) { document.write(substr) } would output 01234, not the segments of the string.
Glenn Nelson
yeah, sorry, my bad, I meant a for loop, as in for(var i=0;i<strArr.length; i++) ... but remember you have to leave the last piece alone as that piece does not end with a "("
pǝlɐɥʞ