Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-仅选择字符串中的特定模式_Javascript_Html - Fatal编程技术网

Javascript-仅选择字符串中的特定模式

Javascript-仅选择字符串中的特定模式,javascript,html,Javascript,Html,我尝试使用以下方法从javascript中的标记中提取字符串: document.querySelector('.title h2').textContent 但我得到的是这样的东西(包括双引号): (很多空格)字符串填充(很多空格) 实际上,我只需要检索字符串中的文本部分(本例中为字符串内容),在双引号和空格后面留下 我知道我需要一些正则表达式,但我不知道在这种情况下如何处理。您可以使用.trim()删除文本内容字符串两侧不需要的空格,如下所示: // "(lots of spaces) St

我尝试使用以下方法从javascript中的标记中提取字符串:

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

但我得到的是这样的东西(包括双引号):

(很多空格)字符串填充(很多空格)

实际上,我只需要检索字符串中的文本部分(本例中为字符串内容),在双引号和空格后面留下

我知道我需要一些正则表达式,但我不知道在这种情况下如何处理。

您可以使用
.trim()
删除
文本内容
字符串两侧不需要的空格,如下所示:

// "(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()
必须告诉replace()重复正则表达式:

.replace(/ /g,'')
g字符表示在整个字符串中重复搜索。了解这一点,以及JavaScript中可用的其他正则表达式修饰符

如果要匹配所有空格,而不仅仅是文字空格字符,请同时使用\s:

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

这不需要正则表达式;您只需使用

console.log(document.querySelector('.title h2').textContent.trim())

一些东西

尝试对字符串使用修剪方法

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

这会消除中间的空格,我想他不想这样。