0

Hey guys i am currently learning javascript, i need to replace "-" with "_". For example : "Hello-World" ==> "Hello_World" i tired the below code it didn't work,i want to know why this method is wrong,

function kS(n){ 
    j=n.length;
    for(i=0;i<j;i++){ 
        if(n[i]=="-")
        {
            n[i]="_"; 
            console.log(n);
        }
    }
}
    

3 Answers3

1

Simply use replace

console.log("Hello-World".replace('-','_'))
Dominik Matis
  • 2,086
  • 10
  • 15
1

You can just use String.replace to achieve that. If you use the regex input in combination with g modifier, it will match all occurences. https://regex101.com/ is a good place to test out such regexes.

var myString = "hello-word";
myString = myString.replace(/-/g, '_');

If you have to do it with a loop and are allowed to use ES2015 or newer, you could also write it like this:

var myString = "hello-word";
var newString = [...myString].map(c => c === '-' ? '_' : c).join('');
pascalpuetz
  • 5,238
  • 1
  • 13
  • 26
0

Stings are immutable. You could convert the string to an array of characters and check and replace the item in the characters array.

At the end return a joined array.

BTW, spelling matter, eg length and undeclared variables are global in Javascript, which should be avoided.

function kS([...characters]) {
    var l = characters.length;
    for (var i = 0; i < l; i++) {
        if (characters[i] === "-") characters[i] = "_";
    }
    return characters.join('');
}

console.log(kS('1-2-3'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392