Jump to content

JavaScript String Replace


kkiranonly

Recommended Posts

Hi,This is KiranKumar and new to this forum.Recently i faced a problem like,I have a String like:var str = "Sony DCR30 PC CAMERA";in JavaScript.So,i want to replace all empty strings in str with "_";I used like :str.replace(\ \,"_");//But it's get affected only for the first space.I mean like this : Sony_DCR30And not for rest of all,and not even displaying the remaining string.So,i require your help in this regards.Is there any other function like(replaceAll() in java) to resolve this issue.Looking forward to recieve an Immediate Response.Thanks for spending your valuable time for me.......RegardsKiran Kumar.K

Link to comment
Share on other sites

a more efficient way would be like this.

var loopProtect = 0; //protect against infinite loopswhile(str.indexOf(" ") != -1 && loopProtect < str.length){    str = str.replace(\ \,"_");    loopProtect++;}

With your code you were looping for the length of the string even if all the spaces were already gone.The code I provided will only loop while there are still spaces present.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...