Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice characters from string using regex?

I have the string AccountDB\\DB.

I want to remove the 4 characters in the end \\DB, so desired result is a string looks like AccountDB.

How can I slice the last four characters using regex?

like image 723
Prajwal Avatar asked Feb 08 '23 16:02

Prajwal


1 Answers

First \\ will be converted to \ in javascript since the backslash sign \ is used to escape the next character, so your string will look like :

"AccountDB\DB"

You could remove the three characters at the end without regex just using slice() function :

"AccountDB\\DB".slice(0, -3); //return AccountDB

alert("AccountDB\\DB".slice(0, -3));

If you need really to use regex you could use :

/(.+)(...)$/
  • . : Matches any character (except newline).

  • + : Between one and unlimited times, as many times as possible

  • (...)$ : Any three characters at end of the string

Hope this helps.


alert("AccountDB\\DB".match(/(.+)(...)$/)[1]);
like image 117
Zakaria Acharki Avatar answered Feb 11 '23 00:02

Zakaria Acharki