0

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.

5
  • Yes, I use js and jQuery. Commented Jun 23, 2014 at 19:26
  • Are you asking about Python or JavaScript? Tags should relate to the question. Commented Jun 23, 2014 at 19:27
  • JavaScript, I am trying to separate an Id-Name from string in jQuery. Commented Jun 23, 2014 at 19:29
  • replace will dump the value found in the regexp Commented Jun 23, 2014 at 19:32
  • Thank you, It works just fine :) Commented Jun 23, 2014 at 19:41

3 Answers 3

1
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 #.

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

Comments

0

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'

Comments

0

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

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

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.