You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写JavaScript函数返回去除指定字符'a'和's'的字符串?

How to Remove All 'a'/'s' (Case-Insensitive) from a String in JavaScript

The cleanest and most efficient way to solve this problem is using a regular expression that targets both lowercase and uppercase versions of 'a' and 's', then replacing all matches with an empty string. Here's a straightforward implementation:

let testString = "AsSverage";

function removeAs(string) {
  // Regex matches 'a', 's', 'A', 'S' globally (all occurrences)
  return string.replace(/[as]/gi, '');
}

// Test the function
console.log(removeAs(testString)); // Output: "verge"

How this works:

  • /[as]/gi is the core of the solution:
    • [as] targets any single character that is either 'a' or 's'
    • The g flag ensures we replace all matching characters (not just the first occurrence)
    • The i flag makes the match case-insensitive, so it catches uppercase 'A' and 'S' too
  • string.replace(...) swaps every matched character with an empty string, effectively removing them from the original string.

Validation with your examples:

  • Input: 'SAverageSsA' → Output: 'verge' (matches your expected result)
  • Input: 'AsaAAs' → Output: '' (empty string, as all characters are in the forbidden set)

Alternative approach (no regex):

If you prefer a more explicit method without regex, you can split the string into characters, filter out unwanted ones, then rejoin:

function removeAs(string) {
  const forbiddenChars = ['a', 's', 'A', 'S'];
  return string.split('')
    .filter(char => !forbiddenChars.includes(char))
    .join('');
}

This method checks each character individually and only keeps those not in the forbidden list—it's a bit more verbose but easy to follow if you're new to regular expressions.

内容的提问来源于stack exchange,提问作者userName

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:22:30