特殊字符串转换 Json格式校验

92 阅读1分钟
  1. 特殊字符串转换
export function unescape(text){
 if(text && text.length>0){
   text = text.replace(/\\t/g,' ');
   text = text.replace(/\\n/g,' ');
   var doc = new DOMParser().parseFromString(text,'text/html');
   return doc.documentElement.textContent
 }
 return text
}

export function unescape1(text){
 if(text && text.length>0){
   text = text.replace(/\\t/g,'');
   text = text.replace(/"/g,'"'); 
   text = text.replace(/&/g,'&'); 
   text = text.replace(/&lt;/g,'<'); 
   text = text.replace(/&gt;/g,'>'); 
   text = text.replace(/&mdash;/g,'--'); 
 }
  return text
}

export function unescape2(text){
 if(text && text.length>0){
   text = text.replace(/\\t/g,' ');
   text = text.replace(/\\n/g,' \n'); // 转成换行的
   var doc = new DOMParser().parseFromString(text,'text/html');
   return doc.documentElement.textContent
 }
  return text
}

// 具体使用 换行的使用

<div style={{ whiteSpace: 'pre-wrap' }}>
 {unescape2('第7条 有效数据:\n (一) 采取执行措施')}
</div>
  1. JSON格式校验方法
const isJson = (str) => {
 if(typeof str === 'string'){
   try {
    const obj = JSON.parse(str);
    if(typeof obj === 'object' && obj){
      return obj
    }else{
     return false;
    }
   }catch(e){
     return false
   }
 }
}

// 判断字符串是不是json字符串
export function isJson (item){
  item = typeof item !== 'string' ? JSON.stringify(item) : item;
  try{
    item = JSON.parse(item);
  }catch(e){
     return false
   }
   if(typeof item === 'object' && item !==null){
     return true
   }
   return false
}