Write a function delchar(s,c) that takes as input strings s and c, where c has length 1 (i.e., a single character), and returns the string obtained by deleting all occurrences of c in s. if c has length other than 1, the function should return s

To create the function delchar(s,c) in JavaScript, you can use the following code:

function delchar(s, c) {
  // Check if c is a single character
  if (c.length !== 1) {
    return s;
  }
  
  // Replace all occurrences of c with an empty string
  return s.split(c).join('');
}

Let’s explain the code:

  • We define a function named delchar that takes two parameters: s and c.
  • Inside the function, we first check if the length of c is not equal to 1. If it is not, we return s as is.
  • If c is a single character, we split the string s using the character c and then join the resulting array using an empty string as the separator. This effectively removes all occurrences of c from s.
  • We then return the modified string.

Here are a few example calls to demonstrate the function:

// Example 1
console.log(delchar("hello world", "l"));
// Output: heo word

// Example 2
console.log(delchar("hello world", "o"));
// Output: hell wrld

// Example 3
console.log(delchar("hello world", "z"));
// Output: hello world

In Example 1, the function removes all occurrences of ‘l’ from the string “hello world”. The resulting string is “heo word”.

In Example 2, the function removes all occurrences of ‘o’ from the string “hello world”. The resulting string is “hell wrld”.

In Example 3, the function returns the original string “hello world” because ‘z’ is not found in it.

Related Post

Leave a comment