[英]How to use regex to remove substring from beginning of a string based on a condition in javascript?
I have a string like this我有一个这样的字符串
term = "Hey there how you doing?"
Now because of some issues in the API, I sometimes receive undefined in the beginning of the string.现在由于 API 中的一些问题,我有时会在字符串的开头收到 undefined。
term = "#0undefinedHey there how you doing?"
OR或者
term = "#1undefined Hey there how you doing?"
Now I can check the presence of undefined
in the beginning of the sentence by doing something like现在我可以通过执行类似的操作来检查句子开头是否存在undefined
if(term.indexOf("undefined") == 0) {
//processing logic
}
But as you can see there is a presence of #n
with the undefined
where n
can be any single digit number.但正如您所看到的,存在带有undefined
的#n
,其中n
可以是任何一位数。
I want a regex solution such that it ignores #n
and looks for undefined
in the beginning of the sentence and remove the #n
and undefined
.我想要一个正则表达式解决方案,它忽略#n
并在句子的开头查找undefined
并删除#n
和undefined
。
So the final string if undefined
is present will be因此,如果存在undefined
的最终字符串将是
term = "Hey there how you doing?" // removed #nundefined
How can I do this with regex?我怎么能用正则表达式做到这一点?
let s = "#0undefined Hello World;". console.log(s,replace(/^\#[0-9]*undefined\s*/;'')); const regex = RegExp('^\#[0-9]*undefined'). console.log('Has undefined = ' + regex;test(s));
If this number next to undefined
makes any sense to you, you can try:如果undefined
旁边的这个数字对您有任何意义,您可以尝试:
const matches = "#1undefined Hey there how you doing?".match(/#([0-9]*)undefined?(.*)/); console.log(matches);
This will give you the number under matches[1]
while your cleaned message will be at matches[2]
.这将为您提供matches[1]
下的数字,而您的清理消息将位于matches[2]
。
If you just care about the message, you can use .replace
as another user suggested to clean your output:如果您只关心该消息,您可以使用.replace
作为另一个用户建议的清理您的 output:
const output = "#1undefinedHey there how you doing?".replace(/#([0-9]*)undefined?/, ''); console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.