Javascript - only select a certain pattern in a string
Javascript - only select a certain pattern in a string
I'm trying to extract a string from a tag in javascript by using :
document.querySelector('.title h2').textContent
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
4
Try using trim method for string.
var a = " String stuff ";
console.log(a.trim()); // Prints: "String stuff"
Here is the documentation.
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,'')
You could use .trim()
to remove the unneeded whitespaces on either side of the textContent
string like so:
.trim()
textContent
// "(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()
:
.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+/, '')
:
.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>
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This will remove spaces in the middle, I don't think he wants that.
– Barmar
Aug 29 at 22:17