1

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!

1
  • Do you want to remove just undefined or the whole string where it appears? Commented Aug 24, 2018 at 18:52

2 Answers 2

2

// 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.*$/, '');
}));

Sign up to request clarification or add additional context in comments.

Comments

2

For both of your example strings this will remove everything after the close paren in the string.

var foo = inputString.replace(/[\w\s]*undefined\s*$/i, '');
  • \w - any of a-z, A-Z, 0-9, _
  • \s - spaces and tabs
  • []* - 0 or more of any pattern inside
  • undefined - the literal "undefined"
  • \s* - 0 or more spaces/tabs
  • $ - end of the string
  • i - everything inside // is case-insensitive (the word 'undefined', in this case)

If you're looking to remove the entire contents of the input if it contains the word undefined then @Toto's answer is the way to go.

1 Comment

Just clarifying for OP, this will remove everything after the last symbol (i.e. close parens)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.