user3417601
user3417601

Reputation: 135

Separating Id from string by using regex

how can I get the first part of ID from the following string?

sText ='DefId #AnyId #MyId';
sText = sText.replace(/ #.*$/g, '');
alert(sText);

The result should be as follows: "DefId #AnyId "

Many thanks in advance.

Upvotes: 0

Views: 57

Answers (3)

Chris Marasti-Georg
Chris Marasti-Georg

Reputation: 34650

var sText ='DefId #AnyId #MyId';
var matches = sText.match(/(DefId #.*) #.*/);
if(matches && matches.length > 0) {
    alert(matches[1]);
}

Move the grouping parenthesis right 1 character if you also want the space after the first ID. This assumes that the IDs won't contain a #.

Upvotes: 1

Aprillion
Aprillion

Reputation: 22330

If you need to get rig of everything after last # in the string, use:

sText.replace(/#[^#]+$/, '');

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174756

You could use this regex,

(.*)#.*?$

DEMO

JS code,

> var sText ='DefId #AnyId #MyId';
undefined
> sText = sText.replace(/(.*)#.*?$/g, '$1');
'DefId #AnyId '

If you don't want any space after #AnyId, then run the below regex to remove that space.

> sText = sText.replace(/(.*) #.*?$/g, '$1');
'DefId #AnyId'

Upvotes: 0

Related Questions