0

I would like to find words in a sentence starting with a prefix and remove the rest of the characters.

Example:

this sentence Type_123 contains a Type_uiy

I would like to remove the characters that come after Type so I can have:

this sentence Type contains a Type

I know how I would go to remove the prefix with regex str.replace(/Type_/g,'') but how do I do the opposite action?

N.B. js prior ES6 if possible

2
  • 1
    str = str.replace(/\b(Type)_\w+/g,'$1') Commented Oct 3, 2018 at 14:12
  • 1
    Or str.replace(/(?<=Type)\w+/g, '') Commented Oct 3, 2018 at 14:15

2 Answers 2

3

Use the expression \b(Type)\w+ to capture the Type prefix.

Explanation:

\b     | Match a word boundary (beginning of word)
(Type) | Capture the word "Type"
\w+    | Match one or more word characters, including an underscore

var str = 'this sentence Type_123 contains a Type_uiy';
var regex = /\b(Type)\w+/g;

console.log(str.replace(regex, '$1'));

The $1 in the replace() method is a reference to the captured characters. In this case, $1 stands for Type. So anywhere in the sentence, Type_xxx will be replaced with Type.

See MDN's documentation on the replace() method.

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

4 Comments

what is $1 for?
Adding a link for the String.prototype.replace() method's documentation(from the Mozilla Developers Network would be better) will help, not only the OP, but anyone who sees your answer.
I completely agree. I'll add it.
@Jonathan However, \b(Type)\w+ will replace Typer with Type, too. If you need to make sure there is an underscore, add it explicitly as in \b(Type)_\w+ , do not rely on \w.
-1

Install: https://github.com/icodeforlove/string-saw

let str = "Here's a sentence that contains Type_123 and Type_uiy";
let result = saw(str)
    .remove(/(?<=Type_)\w+/g)
    .toString();

The above would result in:

"Here's a sentence that contains Type_ and Type_"

Comments

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.