Reputation: 15660
I am trying to use the replace statement in javascript so that ultimately, i can create an array out of some data that is currently passed in a string.
I have the following javascript:
console.log('data from server:' + server_rule_segements);
//remove trailing ~
server_rule_segements = server_rule_segements.substring(0,server_rule_segements.length-2); // stripping off trailing ~,
console.log("1 - " + server_rule_segements);
server_rule_segements = server_rule_segements.replace("~,,", "~");
console.log("2 - " + server_rule_segements);
Here's the results in the console:
data from server:Home Number,1234,1,no~,,Work Number,12342342,1,no~,,Work Number,12344412341234,1,no~,
1 - Home Number,1234,1,no~,,Work Number,12342342,1,no~,,Work Number,12344412341234,1,no
2 - Home Number,1234,1,no~Work Number,12342342,1,no~,,Work Number,12344412341234,1,no
What I'm wondering is why the replace command didn't replace all the instances of "~,,". As you can see in the 2nd debug statement, there's still one there.. in what I'm calling "record 2". I'm sure it's something simple that I've missed... but I can't see it right now.
As I test, I changed the code so that I call the replace method twice, like so:
server_rule_segements = server_rule_segements.replace("~,,", "~");
server_rule_segements = server_rule_segements.replace("~,,", "~");
and then it works. But I don't think I should have to do that.
Upvotes: 0
Views: 228
Reputation: 2763
replace method only replaces first instance, if you want all instances to be replaced use regular expressions. It would be easy because replace method also accepts regular expressions:
server_rule_segements = server_rule_segements.replace(/~,,/g, "~");
would do the trick. Notice the "g" flag means global replace. If you do not want to use regular expressions, use split immediately followed by a join,
server_rule_segements = server_rule_segements.split("~,,").join("~");
Upvotes: 1
Reputation: 1208
String.replace
only replaces the first occurance by default.
You need to change server_rule_segements.replace("~,,", "~");
to server_rule_segements.replace(/~,,/g, "~");
Upvotes: 1
Reputation: 1451
change this:
server_rule_segements.replace("~,,", "~")
to
var re = new RegExp("~,,", 'g');
server_rule_segements.replace(re,"~")
Note i didn't run this code
Upvotes: 0