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,'')





This will remove spaces in the middle, I don't think he wants that.
– Barmar
Aug 29 at 22:17



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế