[英]Find a string inside quotes in Javascript
The title explains my problem.标题说明了我的问题。 I am trying to get a string that has quotation marks around it so I can use Node.js to pass into a weather module.我正在尝试获取一个带有引号的字符串,以便我可以使用 Node.js 传递给天气模块。 Here's my code so far (I have not set the var CityToSearch
yet in this code which is what I need help with) And also yes I'm using Discord.js to send messages.到目前为止,这是我的代码(我还没有在这段代码中设置 var CityToSearch
,这是我需要帮助的)而且是的,我正在使用 Discord.js 发送消息。
const Discord = require('discord.js')
const bot = new Discord.Client()
const PREFIX = '/';
const embed = new Discord.MessageEmbed()
const ping = require('minecraft-server-util')
const weather = require('weather-js')
bot.on('message', message => {
if (message.channel.type === 'dm') {return}
let args = message.content.substring(PREFIX.length).split(' ')
if(message.content.startsWith(PREFIX))
switch (args[0]) {
case 'weather':
if (args.includes('"')){
var CityToSearch =
}
weather.find({search: `city, ${CityToSearch}`, degreeType: 'F'}, function(err, result) {
if(err) console.log(err);
var currentw = new Discord.MessageEmbed()
.setColor(0x00ffff)
.setTitle(`Current Weather in ${args[1]} in state ${args[2]}`)
.addField('Temperature', result[0].current.temperature)
.addField('Sky Text', result[0].current.skytext)
.addField('Humidity', result[0].current.humidity)
.addField('Wind Speed & Direction', result[0].current.winddisplay)
.addField('Feels Like', result[0].current.feelslike)
.addField('Location', result[0].current.observationpoint)
.addField('Time', result[0].current.observationtime)
.addField('Date', result[0].current.date)
message.channel.send(currentw)
});
You can split the actual string with "
. So that the string will be split and the string at index 1
will be the city you are looking for.您可以使用"
拆分实际字符串。这样字符串将被拆分,索引1
处的字符串将是您要查找的城市。
const str = '/weather "San Fransico" California'; console.log(str.split('"')); console.log(str.split('"')[1]);
I would NOT split the arguments on spaces initially.我最初不会在空格上拆分参数。 You can use the Regular Expression below with your arguments to yank out the command, and then parse the inputs as needed:您可以使用下面的正则表达式和您的参数来提取命令,然后根据需要解析输入:
const args = message.content.substring(PREFIX.length).match(/\/([^\s]+) (.+)/)
if (args) { // valid input?
const command = args[1]
const input = args[2]
switch (command) {
case 'weather':
const cityMatch = input.match(/"([^"]+)"/)
const CityToSearch = (cityMatch) ? cityMatch[1] : input.split(/\s/)[0]
weather.find({search: `city, ${CityToSearch}` ...)
// other commands...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.