外观
trim 去除空格
约 258 字小于 1 分钟
2024-01-01
介绍
提供去除字符串空格的工具函数,支持多种去除方式。
trim(str: string, pos?: string): string
- 参数
- str: 需要去除空格的字符串
- pos: 去除空格的位置,可选值:'both'(左右)、'left'(左)、'right'(右)、'all'(所有),默认为 'both'
- 返回值
<String>去除空格后的字符串
示例代码
<template>
<view>
<text>字符串空格去除</text>
<input v-model="inputStr" type="text" placeholder="请输入带空格的字符串" />
<button @click="trimBoth">去除左右空格</button>
<button @click="trimLeft">去除左空格</button>
<button @click="trimRight">去除右空格</button>
<button @click="trimAll">去除所有空格</button>
<view v-if="resultStr">
<text>结果: "{{ resultStr }}"</text>
<text>长度: {{ resultStr.length }}</text>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import { trim } from '@/uni_modules/uview-unix'
const inputStr = ref(' hello world ')
const resultStr = ref('')
const trimBoth = () => {
resultStr.value = trim(inputStr.value)
console.log('去除左右空格:', resultStr.value)
}
const trimLeft = () => {
resultStr.value = trim(inputStr.value, 'left')
console.log('去除左空格:', resultStr.value)
}
const trimRight = () => {
resultStr.value = trim(inputStr.value, 'right')
console.log('去除右空格:', resultStr.value)
}
const trimAll = () => {
resultStr.value = trim(inputStr.value, 'all')
console.log('去除所有空格:', resultStr.value)
}
</script>