简体   繁体   English

在某些情况下替换字符串失败

[英]Replace a string fails in some cases

I must check a string and replace something of them. 我必须检查一个字符串并替换其中的一些内容。

I have to check if 我要检查一下

$mystring='abc...';

has one of this values px,em,%,vh,s 具有以下值之一px,em,%,vh,s

I use this to check the string 我用它来检查字符串

function replaceUnit(input){ return input.replace(/(px|em|%|vh|s)/i ,'') }

It works but produces error in some cases. 它可以工作,但在某些情况下会产生错误。

If I have in my string for example 例如,如果我在字符串中

$mystring="its embeded"

The function will replace the "s" and "em" that's not the way it should be. 该函数将替换原来不应该的“ s”和“ em”。

The function should check if in mystring is 该函数应检查mystring中是否为

only a number+px
or only a number+em
or only a number+%
or only a number+vh
or only a number+s

If there is a match, the function should replace the textpart, in all other cases the function should do nothing. 如果存在匹配项,则该函数应替换textpart,在所有其他情况下,该函数不应执行任何操作。

Is it possible to create a kind of this function and how a replace code must be? 是否可以创建这种功能,以及替换代码必须如何?

Thanks a lot. 非常感谢。

UPDATE UPDATE

based on one of the answears i trie to change it 根据我想要改变的answears之一

var input="0s";
function replaceUnit(input)
{ 
  console.log('check: '+input); 
  var test=input.replace(/(\d)(?:px|em|%|vh|s)$/i ,''); 
  console.log('->: '+test); 
  return test  
}

the result in the console is 控制台中的结果是

check: 0s 
->: 

Add a $ (end-of-string anchor) to the end of the regular expression, to ensure that it'll only match if the characters occur at the very end, and capture a number before those characters, so that you can replace with that number alone (thus stripping out the extra characters): 在正则表达式的末尾添加$ (字符串末尾的锚),以确保仅当字符出现在末尾时才匹配,并在这些字符前捕获一个数字,以便可以替换为仅此数字(从而去除多余的字符):

return input.replace(/(\d)(?:px|em|%|vh|s)$/i ,'$1')

https://regex101.com/r/IodB6z/1 https://regex101.com/r/IodB6z/1

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

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