问题
I am using a regEx expression to filter out the youtube ID of a youtube link. I am using it in two different spots - It works great in the first spot... but the second time I use the same expresion, with the same input, it does not work. Here are the two functions.
First - Here is the one that works. The user inputs the data in a text input, and it returns match[2], which is the youtube ID at the end of the link. The user can copy paste in a whole paragraph of text containing a youtube link, and it still works.
const handleAddVideo = async () => {
if(videoLinkHolder){
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|v=)([^#]*).*/;
var match = videoLinkHolder.match(regExp);
if (match && match[2].length === 11) {
props.addPost(
{
type: "video",
data: match[2],
date: new Date(),
postId: uuidv4(),
rockOn: []
})
props.addYoutube(match[2]);
props.addToSideBar(match[2]);
//Returns the youtube ID
console.log(match[2])
if(props.fbData){
//post to fb
try {
const postText = await fetch(`https://graph.facebook.com/${props.fbData.pageId}/feed?&link=${videoLinkHolder}/&access_token=${props.fbData.pageAccessTokenLong}`, {
method: 'POST'
})
const postTextResponse = await postText.json()
console.log(postTextResponse)
} catch (error) {
console.log(error)
}
}
document.getElementById('videoLinkInput').value = ''
} else {
alert('Sorry! Please use a valid Youtube URL.')
}
}else {
alert('Copy and Paste a Youtube Link Before Submitting!')
}
}
So... Here is my second function. The post comes in from facebook. The object that I receive contains the youtube link.
useEffect(() => {
if(videoLinkHolder.includes('youtu')){
console.log(videoLinkHolder)
//Returns the same paragraph of text I enter on the first function. I can see the youtube link in the console.
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|v=)([^#]*).*/;
var match = videoLinkHolder.match(regExp);
console.log(match[2])
//Returns null
if (match && match[2].length === 11) {
setYoutube(match[2])
console.log(match[2])
}
}
}, [videoLinkHolder])
Again.. I have used exactly the same inputs into both these functions yet the second one still returns null. Can you help?
来源:https://stackoverflow.com/questions/61732102/reg-ex-works-differently-on-two-different-files-of-code