JSK
JSK

Reputation: 1276

conditionally delete numbers from string

I have two types of Strings like the following :

78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180

or

78:27247 PERF create tab state : 1502876879180

I'm looking for a regex to delete the numbers at the start of the string 78:24207

to produice something like this :

PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180

or

PERF create tab state : 1502876879180

and then if the string containt two numbers after the : take only the first number :

PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180

becomes :

PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 

I've tried this replace(/^\d+\.\s*/, ''); for the first pattern but does't seem to work.

and this pattern for the second problem replace(\:.*$) but nothing changed in my string.

Any hints on what I'm doing wrong ?

Upvotes: 2

Views: 72

Answers (5)

SamWhan
SamWhan

Reputation: 8332

As an alternative: don't replace - get the wanted content with match using

[a-z].*:\s*\d+

It matches a letter and everything after it up to a colon, followed by (optional space and) a number.

document.write(
    '78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180'
    .match(/[a-z].*:\s*\d+/i)
);

Upvotes: 1

anubhava
anubhava

Reputation: 785008

You can do this in a single replace call:

var s = '78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180'
var r = s.replace(/^\d+:\d+\s*|(:\s*\d+)\s+\d+$/g, '$1')

console.log(r)

s = '78:27303 PERF tab state created : 1502882663195'
var r = s.replace(/^\d+:\d+\s*|(:\s*\d+)\s+\d+$/g, '$1')

console.log(r)

Upvotes: 2

Matus
Matus

Reputation: 1418

Do you care about the pattern? If not you can just replace first 9 characters using this:

 var str = "78:27247 PERF create tab state : 1502876879180";
 var res = str.replace(/^.{9}/, "");
 console.log(res);

Upvotes: 1

pchaigno
pchaigno

Reputation: 13063

For the first pattern you need:

replace(/^\d+:\d+\s+/, '');

For the second pattern:

replace(/(\s+\d+)\s+\d+$/, '$1');

Upvotes: 1

marvel308
marvel308

Reputation: 10458

You can use it by first matching and then replacing like in the code snippet

function matchAndReplace(str){
	str = str.match(/\d+:\d+ ([\w\s.]*)(:\s*\d+)/g)[0];
	console.log(str.replace(/^\d+:\d+ /,''));
}
matchAndReplace("78:24207 PERF keytouchListAction ProtocolSelect 04.00 : 1502876877199 1502876879180");
matchAndReplace("78:27247 PERF create tab state : 1502876879180");

Upvotes: 1

Related Questions