zoukankan      html  css  js  c++  java
  • js替换字符串中的空格,换行符 或 替换成<br>

    一、为了让回车换行符正确显示,需要将 或 替换成 <br>。同样地,将空格替换存 &nbsp;。这里我们通过正则表达式来替换。

    //原始字符串
    var string = "欢迎访问隔壁老于头!
    cnblogs.com/nljy/    做最好的开发者知识平台";
     
    //替换所有的换行符
    string = string.replace(/
    /g,"<br>")
    string = string.replace(/
    /g,"<br>");string = string.replace(/(
    )|(
    )/g,'<br>');
     
    //替换所有的空格(中文空格、英文空格都会被替换)
    string = string.replace(/s/g," ");
     
    //输出转换后的字符串
    console.log(string);

    二、去掉所有的空格、回车换行符

    //原始字符串
    var string = "欢迎访问隔壁老于头!
    cnblogs.com/nljy/    做最好的开发者知识平台";
     
    //去掉所有的换行符
    string = string.replace(/
    /g,"")
    string = string.replace(/
    /g,"");
     
    //去掉所有的空格(中文空格、英文空格都会被替换)
    string = string.replace(/s/g,"");
     
    //输出转换后的字符串
    console.log(string);
  • 相关阅读:
    Leetcode Unique Binary Search Trees
    Leetcode Decode Ways
    Leetcode Range Sum Query 2D
    Leetcode Range Sum Query
    Leetcode Swap Nodes in Pairs
    Leetcode Rotate Image
    Leetcode Game of Life
    Leetcode Set Matrix Zeroes
    Leetcode Linked List Cycle II
    CF1321A
  • 原文地址:https://www.cnblogs.com/nljy/p/14073694.html
Copyright © 2011-2022 走看看