簡體   English   中英

如何從 Cypress 中的字符串中刪除空格

[英]How to remove whitespace from a string in Cypress

我試圖從代表金錢的數值中刪除空格。

例如,我希望1 000 kr1000 這與貨幣為10 000時的情況相同

我正在使用此函數刪除kr但是當我嘗試添加另一個.replace它不起作用:

Cypress.Commands.add('currency', (selector) => {
      cy.get(selector)
        .children()
        .eq(1)
        .invoke('text') // get text
        .then((text) => +text.replace('kr', '').trim());
    });

我將如何添加另一個 .replace 以從數值中刪除額外的間距? 在此處輸入圖片說明

這應該有效:

function formatString(text) {
    return text.replace('kr', '').replace('\u00A0','').trim();
}

Cypress.Commands.add('currency', (selector) => {
      cy.get(selector)
        .children()
        .eq(1)
        .invoke('text') // get text
        .then(formatString)
    });

但是您也可以使用 Cypress 使用正則表達式字符串來實現此目的(此Cypress FAQ 中的第一個示例與您的示例類似):

Cypress.Commands.add('currency', (selector) => {
      cy.get(selector)
        .should('have.text', '\d+[\u00A0]*')
    });

您可以在此處測試正則表達式: https : //regex101.com/r/YC4szy/1 它將匹配帶有數字的字符串,后跟一個空格,以及任何后續字符。 您可以使用正則表達式來測試您想要的內容。

我的最后一個建議,如果匹配正則表達式模式沒有幫助,您可以將 cypress 命令包裝在一個將文本內容作為參數的函數中,然后將其傳遞到should('have.text', ...)行.

  是一個非中斷空間,與“常規”中斷空間不同:

 const read = sel => document.querySelector(sel).textContent; console.log(read('div') === '1 000 kr'); // false!
 <div>1&nbsp;000 kr</div>

這兩個空白字符實際上具有不同的 ascii 代碼:

 const read = sel => document.querySelector(sel).textContent; const strencode = str => [...str].map(c => c.charCodeAt(0)).join('\\t'); console.log(strencode('1 000 kr')); console.log(strencode(read('div')));
 <div>1&nbsp;000 kr</div>

看看第二個字符有何不同?

您可以使用String#normalize字符串:

 const read = sel => document.querySelector(sel).textContent; console.log(read('div').normalize('NFKC') === '1 000 kr')
 <div>1&nbsp;000 kr</div>

因此,這是您問題的一種可能答案:

  1. 規范化你的字符串
  2. / /g刪除所有空格 (ascii 32) 字符
  3. 刪除末尾的'kr'

 const read = sel => document.querySelector(sel).textContent; const clean = str => str.normalize('NFKC').replace(/ /g, '').replace(/kr$/, ''); console.log(clean(read('#div1'))); console.log(clean(read('#div2')));
 <div id="div1">1&nbsp;000 kr</div> <div id="div2">10&nbsp;000</div>

請參閱JavaScript 字符串中的不間斷空格是如何表示的?

在執行 .text() 時,所有 HTML 實體都被解碼為它們的字符值。

不使用實體進行比較,而是使用實際的原始字符進行比較

if (x == '\\xa0') { // Non-breakable space is char 0xa0 (160 dec)

這將是你正在尋找的表達

+text.replace('kr', '')  
  .replace('\xa0', '')
  .trim()

測試過

<div>1&nbsp;100 kr</div>

為了說明@evolutionxbox 的想法,您可以在element.innerText上使用正則表達式來替換不間斷空格。

Cypress.Commands.add('currency', (selector) => {
  cy.get(selector)   
    .children()
    .eq(1) 
    .then($el => +$el[0].innerText.replace(/\s/g, '').replace('kr', '') )
})

暫無
暫無

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

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