How to check for an "undefined" test present in the string using regex-Javascript

2858 views javascript
2

I'm getting an undefined attached to a string at the end after a regex, something like:

var string="test.testA:(number:'1')undefined' 

and sometimes it gets attached to the string as

var string2 = "test.testA:(number:'1') and undefined"

basically this could be anywhere and I wanted to remove this using regex. Does regex check if there is undefined present in the string? if not what is the best possible soln for this to remove the "undefined" test present in the string?

Thanks!

answered question

Do you want to remove just undefined or the whole string where it appears?

2 Answers

3

For both of your example strings:

var foo = inputString.replace(/[\w\s]*undefined\s*$/i, '');

should work

posted this
4

// remove only "undefined"
var test = [
    "test.testA:(number:'1')undefined",
    "test.testA:(number:'1') and undefined",
];
console.log(test.map(function (a) {
  return a.replace(/\bundefined\b/, '');
}));

// remove the whole line
var test2 = [
    "test.testA:(number:'1')undefined",
    "test.testA:(number:'1') and undefined",
];
console.log(test2.map(function (a) {
  return a.replace(/^.*?\bundefined\b.*$/, '');
}));

posted this

Have an answer?

JD

Please login first before posting an answer.