簡體   English   中英

使用 javascript/jquery 刪除字符串的開頭

[英]Remove beginning of String with javascript/jquery

我正在從一種方法中獲得不斷變化的結果。 它每次都是一個字符串,但在每個字符串的開頭都寫着“String(xxx) “字符串的文本... ”。xxx 取決於字符串內部的字符數。我嘗試使用正則表達式來刪除所有內容在 " 首次出現之前:

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

但我不確定我是否正確使用它。 我也會接受其他方法,在每種情況下都刪除字符串的開頭(與字符串的長度無關)。

例子:

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

我只想在開始時獲得沒有這些東西的字符串,所以:

'This is an example'

但是回報(以及括號中的數字)可能會有所不同。 我想在每種情況下都去掉這個。

您可以使用以下正則表達式來實現這一點:

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

如下:

  • .+ - 一個或任意數量的字符
  • \\)\\s\\" - 直到你到達) "
  • (.*) - 然后捕獲所有內容
  • \\" - 直到你到達最后的"

工作示例:

 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"');

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

證明

解釋

--------------------------------------------------------------------------------
  ^                        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 代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM