Reputation: 145
Currently I have a variable that has turnallplugsoffR1, turnallplugsonR1. I wanted to exclude R1 from the string and get only turnallplugsoff in my variable in nodejs. Could you please help me in achieving the same? dataval="turnallplugsoffR1"
var room_value=dataval.match(/R[0-9]+/i); //matched R1/R2 any other string
console.log(excl); // i want only turnallplugsoff. I dont want R1/R2
console.log(room_value[0]);
Upvotes: 1
Views: 492
Reputation: 626893
You may remove R
followed with any 1+ digits at the end of the string:
var room_value=dataval.replace(/R\d+$/, '')
Details
R
- a R
letter\d+
- 1 or more digits$
- end of string.var dataval="turnallplugsoffR1";
var room_value=dataval.replace(/R\d+$/, '');
console.log(room_value);
You may also get both the values with one matching operation using
dataval.match(/^(.*)(R\d+)$/)
Here, ^
matches the start of the string, (.*)
captures into Group 1 any 0+
chars other than line break chars up to the last R
followed with digits at the end of the string (R\d+)$
capturing the R
+digits into Group 2.
See the JS demo:
var dataval="turnallplugsoffR1";
var res = dataval.match(/^(.*)(R\d+)$/);
if (res) {
console.log(res[1]); // turnallplugsoff
console.log(res[2]); // R1
}
Upvotes: 2
Reputation: 4539
Just split the string with R1 and get the value you want.
dataval="turnallplugsoffR1"
var room_value= dataval.split('R1');
alert(data[0]);
Upvotes: 0