Find and delete words matching a substring in a sentence

Is it possible to use a regular expression to search for all words within a sentence containing a substring?

Example:

var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";

I need to find all words in this sentence that contain "undefined" and delete these words.

Output should be "hello my number is ";

FYI - I'm currently tokenize (javascript) and repeat all tokens to find and delete, and then concatenate the final string. I need to use regex. Please, help.

Thank!

+4
source share
5 answers

It is certainly possible.

Something like the beginning of a word, zero or more letters, "undefined", zero or more letters, the end of a word should do this.

\b , :

\b\w*?undefined\w*?\b

- , , "undefined", .

[a-zA-Z] \w, .

+3

:

str = str.replace(/ *\b\S*?undefined\S*\b/g, '');

- RegEx

+4
\S*undefined\S*

. empty string. .

https://www.regex101.com/r/fG5pZ8/5

+2

, - , :)

, "", , , LARGE

    var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";
    var array = sentence.split(' ');
    var sanitizedArray = [];

    for (var i = 0; i <= array.length; i++) {
        if (undefined !== array[i] && array[i].indexOf('undefined') == -1) {
            sanitizedArray.push(array[i]);
        }
    }

    var sanitizedSentence = sanitizedArray.join(' ');

    alert(sanitizedSentence);

Fiddle: http://jsfiddle.net/448bbumh/

0
source

you can use str.replace function like this

str = str.replace(/undefined/g, '');
0
source

Source: https://habr.com/ru/post/1569672/


All Articles