JavaScript:如何验证字符串是否确实是字符串

标签 javascript string validation

我正在创建一个框架,让开发人员能够使用 XML 中定义的元数据结构创建具有自定义类型的对象:

<class name="Class">
    <attr name="id" type="Yuid" mandatory="true"/>
    <attr name="name"type="YString"/>
</class>

然后在 javascript/typescript 中你可以执行以下操作:

 const instance = new Class({
    name: "bob"
 });

这个想法是向类属性生成器添加验证器以断言 XML 模式有效。

对于简单的基元,我使用了像 str = new String(str) 这样的基元构造函数,直到我们在显示此数据时开始遇到一些奇怪的问题。举例说明:

const thang = new String("thang");
const theng = String("theng");
const thing = "thing";
const thong = String({ rick: "sanchez" });
const thung = new String({ rick: "sanchez" });

console.log(thang, typeof thang); // [String: 'thang'] 'object
console.log(theng, typeof theng); // theng string
console.log(thing, typeof thing); // thing string
console.log(thong, typeof thong); // [object Object] string
console.log(thung, typeof thung); // [String: '[object Object]'] 'object'

console.log({}.toString(), typeof {}.toString()); // [object Object] string
console.log("abc".toString(), typeof "abc".toString()); // abc string
console.log([1, 2, 3].toString(), typeof [1, 2, 3].toString()); // 1,2,3 string
console.log((5).toString(), typeof (5).toString()); // 5 string

console.log(`thang is ${thang}`); // thang is thang
console.log(`theng is ${thang}`); // theng is theng
console.log(`thing is ${thang}`); // thing is thing
console.log(`thong is ${thong}`); // thong is [object Object]
console.log(`thung is ${thung}`); // thung is [object Object]

TypeScript 提示是相同的,在所有情况下我都会得到字符串,但现实有点不同,所以我如何完全确定我可以将任何值转换为字符串?

最佳答案

而不是使用:

const thang = new String("thang");

用途:

const thang = "thang";

关于JavaScript:如何验证字符串是否确实是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55171856/

相关文章:

regex - 非典型密码验证正则表达式 : at least 3 letters, 3 个数字,无双引号

javascript动态提交时更改表单

c# - 我如何从字符串创建 Lambda 表达式

Java:如何将字符串中的每个字符转换为 '*'(空格除外)

c++ - 分解长字符串

javascript - 如何防止页面逐渐显示?

Javascript 根据所需的字符集(编码)验证用户输入

javascript - 函数在第二次单击之前不打开弹出窗口

java - JSNI:JavaScriptObject 和 Element JSNI 函数参数的区别?

javascript - 没有框架,动画的Javascript幻灯片放映?