-1

I have create a sentence "my name , is , shahab". I want to remove both comma's. I removed one comma.Can any one help me to remove the other comma and show the sentence "my name is shahab".

<!DOCTYPE html>
<html>
<head>
 <title>Helpful functions</title>
</head>
<body>
 <div>
  <h2>Hello my name is Babloo</h2>
 </div>
 <script type="text/javascript">

  let alpha = "my name , is , shahab";
  let al = alpha.split(" ");
  let index = al.findIndex((c)=>{
   return c == ','
  })
  al.splice(index,1)

  alpha = al.join(" ");
  console.log(alpha)


 </script>
</body>
</html>
Shahab Khan
  • 929
  • 1
  • 10
  • 17
  • 1
    I wonder why the question was downvoted? Sure it may be a dupe, but it's a well asked question – musefan Apr 11 '18 at 09:10
  • 1
    To be clear, do you **have** to use `split`? Or are you OK to use regex with replace function? – musefan Apr 11 '18 at 09:11

3 Answers3

1

You can avoid using split and splice. Simply, use replace in global scope

USING REPLACE

var str = 'my name , is , shahab';
var res = str.replace(/\, /g, '');
console.log(res);

USING SPLIT AND JOIN

let str = "my name , is , shahab";
var res  = str.split(',').join('');
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

You can split by ,(comma) into arrays and then join them

let alpha = "my name , is , shahab";
alpha = alpha.split(",").join("");
console.log(alpha);
sridhar..
  • 1,945
  • 15
  • 19
1

You can either call .replace(‘,’, ””) twice or preferably write your own replaceAll function using regular expressions:

function(search, replacement) {
    return this.replace(new RegExp(search, ‘g’), replacement);
}