remove first two character from string and space: 从字符串中移除前两个字符和空格

huangapple go评论71阅读模式
英文:

how to remove first two character from string and space

问题

如果有人帮我。

我尝试用以下语法将第一个"aa"和"ab"替换为空格:

replace(/^(.){2}/,'').trim(),但不起作用。

就像我尝试删除第一个"aa"和"ab",只打印"hello world",但使用这个语法不起作用:

let check = 'aa hello world'
let check = 'ab hello world'

英文:

If any body help me out.

i tried two replace first aa and ab with space with this syntax
replace(/^(.){2}/,'').trim() but not work.

like i have tried to remove first aa and ab only print hello word but not work with this syntax
let check = 'aa hello world'
let check = 'ab hello world'

答案1

得分: 3

以下是一个例子,只需添加一个IF语句来检查字符串是否以aa或ab开头:

var check = 'aa 你好 世界';

if (check.startsWith('aa') || check.startsWith('ab')) {
  check = check.substring(3);
}

你甚至可以保留你的代码:

var check = 'aa 你好 世界';

if (check.startsWith('aa') || check.startsWith('ab')) {
  check = check.replace(/^(.){2}/,'').trim()
}

console.log(check)

答案:

"你好 世界"
英文:

Here is an example just adding an IF statement to see if the string starts with aa or ab:

 var check = 'aa hello world';

 if (check.startsWith('aa') || check.startsWith('ab')) {
   check = check.substring(3);
 }

You can even keep your code:

var check = 'aa hello world';

if (check.startsWith('aa') || check.startsWith('ab')) {
  check = check.replace(/^(.){2}/,'').trim()
}

console.log(check)

Answer:

 "hello world"

答案2

得分: 0

你可以尝试使用[slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)

    let text = "aa 你好,世界!";
    if (text.startsWith('aa') || text.startsWith('ab')) {
     text = text.slice(3);
    }

结果:

    你好,世界!
英文:

Can you try using slice

let text = "aa hello world!";
if (text.startsWith('aa') || text.startsWith('ab')) {
 text = text.slice(3);
}

Result:

hello world

huangapple
  • 本文由 发表于 2023年3月31日 16:35:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定