修改以下代码,要求当nameAndsrc为true时匹配下划线前的字符,nameAndsrc为false时匹配下划线后的字符:function addFileExtension(str) { var pattern = nameAndsrc ? /^\s+(?=-)/ : /-(.*)(\.jpg|\.png)/; //判断读取状态改变正则 var match = str.match(pattern); return match ? `${match[1]}${match[2]}` : str; }
时间: 2023-08-13 11:04:32 浏览: 37
请尝试使用以下修改后的代码:
```javascript
function addFileExtension(str, nameAndsrc) {
var pattern = nameAndsrc ? /^([^\s_]+)(?=_)/ : /_(.*)(\.jpg|\.png)$/;
var match = str.match(pattern);
return match ? `${match[1]}${match[2]}` : str;
}
```
修改后的代码中,我们将原本的正则表达式进行了修改,根据传入的 `nameAndsrc` 参数来匹配下划线前或下划线后的字符。同时,我们还修改了正则表达式中的一些细节,使之更符合我们的需求。最后,我们在函数定义中加上了 `nameAndsrc` 参数,以便更好地控制函数的行为。
相关问题
前端如何匹配字符串中含:的字符并且返回true
可以使用JavaScript中的includes()方法来检查字符串是否包含特定字符。例如,如果要检查字符串中是否包含冒号字符“:”,可以使用以下代码:
```
let str = "this is a string: with a colon";
if (str.includes(":")) {
console.log("The string contains a colon");
} else {
console.log("The string does not contain a colon");
}
```
当字符串中包含冒号时,代码将输出“The string contains a colon”,否则将输出“The string does not contain a colon”。
用python查找字符串pdfName中,是否存在下划线,是返回true,否返回false
下面是一个Python函数,用于检查给定字符串中是否存在下划线。如果存在,则返回True;否则返回False。
```python
def check_underscore(pdfName):
if "_" in pdfName:
return True
else:
return False
```
你可以调用这个函数,并传递一个字符串参数来检查该字符串中是否包含下划线。例如:
```python
pdfName = "example_file.pdf"
if check_underscore(pdfName):
print("The filename contains an underscore.")
else:
print("The filename does not contain an underscore.")
```
运行上面的代码,将打印出字符串“ The filename contains an underscore.”,因为字符串“ example_file.pdf”中包含一个下划线。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)