jciaurriz_iar
jciaurriz_iar

Reputation: 23

Remove part of the string before the FIRST dot with js

I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:

var str = "P001.M003.PO888393"; 
str = str.split(".").pop();

But the result of str is "PO888393".

I need to remove only the part before the first dot. I want next result: "M003.PO888393".

Someone knows how can I do this? Thanks!

Upvotes: 1

Views: 5345

Answers (6)

Géry Ogam
Géry Ogam

Reputation: 8027

Using String.prototype.replace() on a RegExp with the non-greedy quantifier *?:

> 'P001.M003.PO888393'.replace(/.*?\./, '')
'M003.PO888393'

Upvotes: 0

spaceSentinel
spaceSentinel

Reputation: 670

One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.

let str = "P001.M003.PO888393"; 
str = str.substring(str.indexOf('.')+1);
console.log(str)

Upvotes: 6

Nick Parsons
Nick Parsons

Reputation: 50684

You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.

var str = "P001.M003.PO888393"; 
var res = str.replace(/^[^\.]*\./, '');
console.log(res);

Regex explanation:

  • ^ Match the beginning of the string
  • [^\.]* match zero or more (*) characters that are not a . character.
  • \. match a . character

Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.

Upvotes: 2

Kidas
Kidas

Reputation: 329

many way to achieve that:

  • by using slice function:
    let str = "P001.M003.PO888393";
    str = str.slice(str.indexOf('.') + 1);
    let str = "P001.M003.PO888393"; 
    str = str.substring(str.indexOf('.') + 1);
  • by using substr function
    let str = "P001.M003.PO888393";
    str = str.substr(str.indexOf('.') + 1);
  • and ...

Upvotes: 0

Alan Omar
Alan Omar

Reputation: 4217

calling replace on the string with regex /^\w+\./g will do it:

let re = /^\w+\./g
let result =  "P001.M003.PO888393".replace(re,'')
console.log(result)

where:

  • \w is word character
  • + means one or more times
  • \. literally .

Upvotes: 0

dns_nx
dns_nx

Reputation: 3943

You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:

str = str.split('.').splice(1).join('.');

Result is

M003.PO888393

var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);

Upvotes: 1

Related Questions