开发者

regex in javascript

开发者 https://www.devze.com 2023-04-02 20:19 出处:网络
I have a input string like lo0.1 and lo0.2 and lo0.0. I want to replace .0,.1 and .2 to null. So basically i want the output to be lo0 when its lo0.1 and lo0.2 and lo0.0.

I have a input string like lo0.1 and lo0.2 and lo0.0.

I want to replace .0,.1 and .2 to null. So basically i want the output to be lo0 when its lo0.1 and lo0.2 and lo0.0.

I am using below code:

var reg = '\d';
if(port_key.getString().contains('.'+'reg')){
    //parent_port_key.getString().setValue(port_key.getString());
parent_port_key.setValue(port_key.getString());
parent_port_key=(parent_port_key).replace('.'+'reg','');
}
开发者_运维问答

Please let me know why it is not working.. What else i can do.


Something like this:

var str = "lo0.1 and lo0.2 and lo0.0";
str.replace(/(\.\d)/g, '');


. is a reserverd regex char representing any char. you need to escape it with a backslash also reg is variable holding a string, so dont put it in parantheses

so it should be contains and replace '\.'+reg


About regular expression I can suggest you the following web site: enter RegEx LIB.

It contains many regular expressions (the link I sent you is directly for String category). Moreover you can test your regular expressions (also using Client Side engine - Javascript).

I am sure there you can find your wished regular expression and you can also refer to it everytime you will need a new one.

I use it every time I need RegEX in my projects.


You can use this regex /\.\d$/ to replace a trailing .n like this:

var test = "lo0.2";
var output = test.replace(/\.\d$/, "");
alert(output);   // "lo0"

This one regular expression will work for all single digit values. If you need it to work for multiple digit values, that can be done too with /\.\d+$/.

By way of explanation, the regular expression says to match a period followed by a digit followed by the end of the string and replace that with nothing (which will remove it from the end of the string). The backslash in front of the period is required because the period itself is a special regex character so to match a literal period, we have to escape it with the backslash.

I don't know exactly what you're trying to do in your code, but I think you could do something like this:

var re = /\.\d$/;
if (port_key_getString().search(re) != -1) {
    parent_port_key.setValue(port_key_getString().replace(re, ""));
}


Try this:

s = "lo0.1";
s = s.replace(/\.\d$/, "");

You should delimit the regexes between slashes, not quotes.

0

精彩评论

暂无评论...
验证码 换一张
取 消