简体   繁体   English

用regexp替换返回undefined

[英]replace with regexp return undefined

I'm not so bad in regular expression but there I have a tiny problem, maybe one of you can answer this simple question. 我在正则表达方面并不是那么糟糕,但我有一个小问题,也许你们其中一个人可以回答这个简单的问题。

I do this: 我这样做:

var myString = "10px";
var myRegexp = new RegExp("(\\d*\\.?\\d*){1}(em|ex|grad|ch|deg|ms|rad|rem|s|turn|vh|vw|vmin|vmax|px|cm|in|pt|pc|%)?", "gi");

myString.replace(myRegexp, function( match, number, type ){
    console.log(match, number, type);
});

The replace console log two time, the first is : "10px", "10", "px" and I don't know why there is a second time, it return me that: ,,undefined (the two first value are not null or empty string, they return just nothing, absolutely empty). 替换控制台日志两次,第一次是: "10px", "10", "px" ,我不知道为什么还有第二次,它还给我那个: ,,undefined (两个第一个值不是null或空字符串,它们只返回任何内容,绝对是空的)。

My question, why the replace try a seconde replacing on nothing ? 我的问题,为什么替换尝试替换没有任何东西? And how avoid it ? 怎么避免呢?

Instead of: 代替:

 (\\d*\\.?\\d*){1}

Use start anchor: 使用开始锚点:

^(\\d*\\.?\\d*)

As your regex has everything optional and matches empty string also. 因为你的正则表达式具有可选的所有内容并且也匹配空字符串。

I think it is because your expression has everything optional, so you are also matching a zero-length string (an issue with javascript). 我认为这是因为你的表达式具有可选的所有内容,所以你也匹配一个零长度的字符串(javascript的一个问题)。 If I understand what you want to do, I don't think the number has to be optional, so you could try: 如果我理解你想做什么,我不认为这个号码必须是可选的,所以你可以尝试:

(\d*\.?\d+)(em|ex|grad|ch|deg|ms|rad|rem|s|turn|vh|vw|vmin|vmax|px|cm|in|pt|pc|%)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM