Reputation: 135
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
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
Reputation: 22330
If you need to get rig of everything after last #
in the string, use:
sText.replace(/#[^#]+$/, '');
Upvotes: 0
Reputation: 174756
You could use this regex,
(.*)#.*?$
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