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
- Cannot invoke “java.sql.connection.preparestatement(string)” because “con” is null
- The constructor being called isn’t a const constructor.
- Bad state: field does not exist within the documentsnapshotplatform
- ‘react/rctdefines.h’ file not found
- Wrapped into a reference object to be modified when captured in a closure