简体   繁体   中英

Remove beginning of String with javascript/jquery

I'm getting changing results from a method. It is everytime a String, but at the beginning of every String is written "String(xxx) "Text of String... ". The xxx depends on the number of characters inside of the String. I tried using regex to cut everything away before first appearance of " :

(result.replace(/^.+?(\\") /, ''))

But I'm not sure if I used it correctly. I would also accept other approaches, which delete the beginning of the String in every case (independently of the length of the string).

Example:

return String: 'string(18) "This is an example"'

And I just want to get the String without the stuff at the beginning, so:

'This is an example'

But the return (and therefore the number in the parenthesis) can vary. I want to cut this out in every case.

You can achieve this with the following regex:

/.+\)\s\"(.*)\"/

As follows:

  • .+ - one or any number of characters
  • \\)\\s\\" - until you reach ) "
  • (.*) - then capture everything
  • \\" - until you reach the final "

Working Example:

 const processString = (string) => { let processedString = string.replace(/.+\\)\\s\\"(.*)\\"/, '$1'); console.log(processedString); } processString('string(18) "This is an example"'); processString('string(23) "This is another example"'); processString('string(25) "This is a "third" example"');

Use

string.replace(/^.*? "|"$/g, '')

See proof .

Explanation

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
--------------------------------------------------------------------------------
   "                       ' "'
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  "                        '"'
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

JavaScript code:

 const string = 'string(18) "This is an example"'; console.log(string.replace(/^.*? "|"$/g, ''));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM