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
- Get the text from an element. In Selenium, use
element.getText()(WebDriverIO) orelement.text(Selenium WebDriver for Node). Store it in a variable:const headerText = await $('h1').getText(); - Check if a string contains a substring. Use
.includes()for simple checks:expect(headerText).to.include('Welcome');orif (headerText.includes('error')) { ... } - 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 #”. - 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. - Split a string into an array. Use
.split()on a delimiter:const items = listText.split(',');Then iterate withforEachor checkitems.length. - Trim whitespace. Use
.trim()to remove leading/trailing spaces:const trimmed = elementText.trim();Essential before comparing to expected values. - Convert case. Use
.toUpperCase()or.toLowerCase()for case-insensitive comparisons:expect(buttonText.toLowerCase()).to.equal('submit'); - 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”. - Find the position of a character. Use
.indexOf():const atPos = email.indexOf('@');Returns -1 if not found. - Build strings dynamically. Use template literals (backticks) for readability:
const expectedUrl = `https://example.com/user/${userId}`;Avoid messy concatenation. - Pad or repeat strings (rare but useful). Use
.padStart()for fixed-width numbers:String(5).padStart(2, '0')gives “05”. - Check if a string starts or ends with something. Use
.startsWith()and.endsWith():if (url.startsWith('https://')) { ... } - Convert a string to a number. Use
parseInt()orparseFloat()when extracting numeric values:const price = parseFloat(priceText.replace('$', '')); - Compare strings properly. Use
===for exact matches, but beware of whitespace and case. Always trim and normalize before comparing. - Use string methods in assertions. Combine with your test framework’s assertions:
expect(alertText).to.contain('success');orassert.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 meantreplaceAll(). The former only replaces the first match. Use a global regex/old/gorreplaceAll(). - Ignoring null/undefined. Calling
.includes()onnullthrows 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
- How to Reset Snapchat Password (Step-by-Step)
- View Taskbar Settings Windows 10: A Complete Guide
- 0x6d9 Windows Firewall Error: Step-by-Step Fix
- Fix Outlook Not Receiving Emails on Mac
- 5G Battery Drain Fix: Android Settings That Work
- How to Turn On/Off iPhone Vibration