0

String method problem

How can I solve this exercise? I ask user to enter a string and I have to show It separated by ("-") using any String method in a simple way. E.g. user enters Hello World and I show It as H-e-l-l-o-W-o-r-ld

22nd Oct 2020, 11:28 PM
ASENCIO ORTIZ SAEZ
9 Respostas
+ 6
One way to do it, str="Hello World" str=str.replace(/ /g,"") console.log([...str].join("-")) replace method with regex / /g will find all ocuurences of space and remove them Then you can spread string into an Array of characters, (...is a spread operator for expanding an iterable into individual elements and yes string is an iterable as it is an array of characters in actual) After that use join method
22nd Oct 2020, 11:55 PM
Abhay
Abhay - avatar
+ 5
Hi,Mention the language name in tags
22nd Oct 2020, 11:29 PM
Abhay
Abhay - avatar
+ 4
Another way to do, let str = "Houston we have a problem ..."; console .log(str.replace(/ /g, "").split("").join("-"))
23rd Oct 2020, 12:55 AM
Ipang
23rd Oct 2020, 6:16 AM
ODLNT
ODLNT - avatar
+ 1
There's no another easiest way to do It? Not using regex
23rd Oct 2020, 2:17 AM
ASENCIO ORTIZ SAEZ
+ 1
Another way to do, let str = "Houston we have a problem ..."; console .log(str.replace(" ", "").split("").join("-"))
23rd Oct 2020, 3:15 AM
🇼🇳Vivek🇼🇳
🇼🇳Vivek🇼🇳 - avatar
+ 1
ASENCIO ORTIZ SAEZ Your output example shows that spaces between words are to be removed. But when I tried to replace spaces with blanks without regex, only one of the spaces were removed. The rest of the spaces remained. If you don't mind the spaces, then no regex needed, just use `replace`, `split` and `join`method.
23rd Oct 2020, 3:41 AM
Ipang
0
Javascript ,I forgot to mention that
22nd Oct 2020, 11:31 PM
ASENCIO ORTIZ SAEZ
0
Ok,I will try that guys,thx
23rd Oct 2020, 4:49 AM
ASENCIO ORTIZ SAEZ