sodcalculator

10 Tech How-To

JavaScript String Methods for Selenium Tests

Guide 10-60832 · Updated · Step by step

Working with strings is a daily task in Selenium test automation. Asserting text, building dynamic selectors, and parsing UI output all depend on solid string handling. This guide covers the essential JavaScript string methods you’ll use inside your Selenium test scripts, with practical examples you can apply immediately.

What You’ll Need

  • A Selenium test environment (WebDriver + a test runner like Mocha, Jest, or a plain Node script)
  • Basic familiarity with JavaScript syntax
  • Access to a page with text elements you can locate for practice

Step-by-Step

  1. Get the text from an element. In Selenium, use element.getText() (WebDriverIO) or element.text (Selenium WebDriver for Node). Store it in a variable: const headerText = await $('h1').getText();
  2. Check if a string contains a substring. Use .includes() for simple checks: expect(headerText).to.include('Welcome'); or if (headerText.includes('error')) { ... }
  3. Match patterns with regular expressions. Use .match() with a regex to extract parts: const orderNumber = bodyText.match(/Order #(\d+)/)[1]; This grabs the digits after “Order #”.
  4. Replace text in a string. Use .replace() for the first occurrence or .replaceAll() for all: let cleanText = rawText.replace(/\s+/g, ' '); collapses multiple spaces into one.
  5. Split a string into an array. Use .split() on a delimiter: const items = listText.split(','); Then iterate with forEach or check items.length.
  6. Trim whitespace. Use .trim() to remove leading/trailing spaces: const trimmed = elementText.trim(); Essential before comparing to expected values.
  7. Convert case. Use .toUpperCase() or .toLowerCase() for case-insensitive comparisons: expect(buttonText.toLowerCase()).to.equal('submit');
  8. Extract a substring by position. Use .substring(start, end) or .slice(start, end): const year = dateText.substring(0, 4); for “2025-03-14” gives “2025”.
  9. Find the position of a character. Use .indexOf(): const atPos = email.indexOf('@'); Returns -1 if not found.
  10. Build strings dynamically. Use template literals (backticks) for readability: const expectedUrl = `https://example.com/user/${userId}`; Avoid messy concatenation.
  11. Pad or repeat strings (rare but useful). Use .padStart() for fixed-width numbers: String(5).padStart(2, '0') gives “05”.
  12. Check if a string starts or ends with something. Use .startsWith() and .endsWith(): if (url.startsWith('https://')) { ... }
  13. Convert a string to a number. Use parseInt() or parseFloat() when extracting numeric values: const price = parseFloat(priceText.replace('$', ''));
  14. Compare strings properly. Use === for exact matches, but beware of whitespace and case. Always trim and normalize before comparing.
  15. Use string methods in assertions. Combine with your test framework’s assertions: expect(alertText).to.contain('success'); or assert.strictEqual(trimmedText, expected);

Common Mistakes

  • Forgetting to trim. UI text often has trailing newlines or spaces. "Hello ".trim() is not equal to "Hello" without trimming.
  • Using == instead of ===. Loose equality can cause type coercion surprises. Always use strict equality for strings.
  • Assuming case sensitivity. “Submit” and “submit” are different. Normalize with toLowerCase() when case doesn’t matter.
  • Using replace() when you meant replaceAll(). The former only replaces the first match. Use a global regex /old/g or replaceAll().
  • Ignoring null/undefined. Calling .includes() on null throws an error. Check the element exists first: if (element && element.getText()).
  • Hardcoding expected strings. If the UI changes slightly, tests break. Consider using regex or partial matches where appropriate.

Tips

  • Use template literals for building dynamic selectors and URLs. They’re cleaner and less error-prone.
  • Create a helper function for common operations, like getTextAndTrim(locator), to avoid repeating code.
  • Use regex wisely — test them in a separate console first. A small regex mistake can cause false failures.
  • When extracting numbers, always remove currency symbols, commas, and spaces before parsing: parseFloat(text.replace(/[^\d.-]/g, '')).
  • For long strings, use substring or slice to isolate the part you need rather than doing complex regex.
  • Log the actual string values in test failures — it makes debugging much faster.

Troubleshooting

Test fails with “Expected ‘X’ to include ‘Y'” but the text looks right. Check for hidden whitespace. Log the actual value with JSON.stringify(text) to see escaped characters. Trim both sides before comparing.

Regex returns null and the test crashes. Use optional chaining: const match = text.match(/.../); const value = match ? match[1] : ''; Or use .search() to check existence first.

String is empty when you expect text. The element might be hidden or not yet rendered. Add a wait: await element.waitForDisplayed() before reading text.

parseInt gives NaN. The string may contain non-numeric characters. Remove them first, or use Number(text) after cleaning.

Case-insensitive comparison fails. Ensure both sides are converted: actual.toLowerCase() === expected.toLowerCase(). Also consider locale-specific issues with toLocaleLowerCase() for special characters.

Element text includes child element text. Use .getText() on the specific child, or select the parent and subtract known child text if needed.

Frequently Asked Questions

How do I get text from an element that contains multiple lines?

Use getText() — it returns the full text including newlines. You can then split on \n to get an array of lines.

What’s the difference between substring() and slice()?

They behave identically for positive indices. slice() also accepts negative indices (counting from the end), while substring() treats negatives as 0.

Can I use regular expressions with includes()?

No. includes() only does literal substring checks. Use .match() or .test() on a RegExp object for pattern matching.

How do I handle strings with special characters like emojis or accented letters?

JavaScript strings are UTF-16. Most methods work fine. For normalization (e.g., é vs e + accent), use String.prototype.normalize() before comparing.

Is there a way to check if a string is empty or whitespace-only?

Yes: if (!text.trim()) { ... } — this is true for empty, spaces, tabs, and newlines.

How do I extract a number from a string like “Price: $1,234.56”?

Use parseFloat(text.replace(/[^\d.-]/g, '')). This removes everything except digits, minus, and decimal point, giving you 1234.56.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →