js判断字符串是否以post开头
时间: 2023-12-16 15:03:39 浏览: 31
可以使用JavaScript中的startsWith()方法来判断字符串是否以指定的前缀开始。示例代码如下:
```javascript
const str = "post请求";
if (str.startsWith("post")) {
console.log("字符串以post开头");
} else {
console.log("字符串不以post开头");
}
```
输出结果为:字符串以post开头。
相关问题
js,如果字符串以post开头取post之后的部分
可以使用JavaScript中的substr()或slice()方法来截取字符串。示例代码如下:
```javascript
const str = "post请求";
if (str.startsWith("post")) {
const result = str.substr(4); // 或者使用 str.slice(4)
console.log("取post之后的部分:" + result);
} else {
console.log("字符串不以post开头");
}
```
输出结果为:取post之后的部分:请求。
js post发送字符串
可以使用 XMLHttpRequest 或 fetch 发送 POST 请求,并将字符串作为请求体发送。
使用 XMLHttpRequest:
```
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send(str);
```
使用 fetch:
```
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: str
});
```
其中,`url` 是请求的地址,`str` 是要发送的字符串。`Content-Type` 是请求体的类型,需要设置为 `text/plain`。