Javascript - only select a certain pattern in a string

Viewed 211

I'm trying to extract a string from a tag in javascript by using :

document.querySelector('.title h2').textContent

But I get something like this (double quotes included) :

"(lots of spaces) String stuff (lots of spaces)"

and I actually need to retrieve only the text part (String stuff in this example) in the string, lefting behind the double quotes and the spaces.

I know I'll need some regex, but I don't know how to proceed in that case.

4 Answers

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s as well:

.replace(/\s/g,'')

Try using trim method for string.

var a = "    String stuff    ";
console.log(a.trim());       // Prints: "String stuff"

Here is the documentation.

You could use .trim() to remove the unneeded whitespaces on either side of the textContent string like so:

// "(lots of spaces) String stuff (lots of spaces)"
document.querySelector('.title h2').textContent

// Add .trim() to get "String stuff"
document.querySelector('.title h2').textContent.trim()

You don't need a regex for this; you can simply use .trim():

console.log(document.querySelector('.title h2').textContent.trim());
<div class="title">
 <h2>   Some stuff    </h2>
</div>

If you really want to use a regex, you can use .replace(/\s+/, ''):

const input = document.querySelector('.title h2').textContent;
const output = input.replace(/\s+/, '');

console.log(output);
<div class="title">
 <h2>   Some stuff    </h2>
</div>

Related