如何只在字符串的开头部分查找/替换不区分大小写?

时间:2021-05-03 19:19:00

I want to remove "I will" at the beginning of a string. Those "I will" words could be uppercase/lowercase, so I will need to match for case insensitive. But I only want to remove those words if they are at the beginning of the string.

我想在字符串的开头删除“我会”。那些“我会”的单词可能是大写/小写,所以我需要匹配不区分大小写。但是我只想删除这些单词,如果它们位于字符串的开头。

I tried .replace(), but that doesn't take into account the situations above.

我尝试过.replace(),但这没有考虑到上面的情况。

1 个解决方案

#1


3  

Use the ignore case flag i:

使用ignore case标志i:

var x = "I will write good code";

// the ^ at the start tells it to match from the beginning
// the i flag tells it to ignore case
x = x.replace(/^i\s+will\s+/i, '');

// Outputs: "write good code" regardless of the case of "i will"

#1


3  

Use the ignore case flag i:

使用ignore case标志i:

var x = "I will write good code";

// the ^ at the start tells it to match from the beginning
// the i flag tells it to ignore case
x = x.replace(/^i\s+will\s+/i, '');

// Outputs: "write good code" regardless of the case of "i will"