Reputation: 23
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
Reputation: 8027
Using String.prototype.replace()
on a RegExp
with the non-greedy quantifier *?
:
> 'P001.M003.PO888393'.replace(/.*?\./, '')
'M003.PO888393'
Upvotes: 0
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
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 .
characterUsing these combined matches the first characters in the string include the first .
, and replaces it with an empty string ''
.
Upvotes: 2
Reputation: 329
many way to achieve that:
slice
function: let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
substring
function let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
substr
function let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
Upvotes: 0
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
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