简体   繁体   English

在一个字符串中,如何检查另一个字符前面的前一个字符是否是空格?

[英]Within a string, how to check whether the previous character ahead of another one is a space?

Am facing a situation that is hard to describe.我面临着难以描述的情况。 Will explain and correct me if am wrong如果错了会解释并纠正我

I do have a string我有一个字符串

String 1 - I am: learning javascript ( no space before : )
String 2 - I am: learning javascript (1 space after : )

Condition am doing is first I need to check whether a string has 1 colon only if the string has only 1 colon , if so, then check whats the element coming in front of colon, if it does have space don't do anything and if it ** doesn't have space**, add a space我正在做的条件是首先我需要检查一个字符串是否只有 1 个冒号,如果该字符串只有1 个冒号,如果是,那么检查冒号前面的元素是什么,如果它确实有空格,不做任何事情,如果它**没有空格**,添加一个空格

I got the occurrence of finding 1 colon in a string like我在类似的字符串中发现了 1 个冒号

  term.indexOf(':') === term.lastIndexOf(':')) ||
 (term.match(new RegExp(":", "g")) || []).length===1) {

But I am not getting whats the character coming ahead of the colon, if it %20 (space), don't do anything, if NOT %20 ( i mean not space) ADD a space但我没有得到冒号前面的字符是什么,如果它是 %20(空格),不要做任何事情,如果不是%20(我的意思是不是空格)添加一个空格

Am sorry if any confusions happen, I can explain if any more info is needed很抱歉,如果发生任何混淆,我可以解释是否需要更多信息

Thanks in advance提前致谢

Maybe you could use:也许你可以使用:

^([^:]*(?<!\s)):([^:]*)$

This would check if a string only contains a single colon that is not preceded by a space character.这将检查一个字符串是否只包含一个冒号,并且前面没有空格字符。 The different parts are captured in groups so you can replace this by: $1:$2 .不同的部分被分组捕获,因此您可以将其替换为: $1:$2

See the online demo查看在线演示

  • ^ - Start string anchor. ^ - 开始字符串锚。
  • ( - Open 1st capture group: ( - 打开第一个捕获组:
    • [^:]* - 0+ times any character other than colon. [^:]* - 0+ 次除冒号以外的任何字符。
    • (?<!\s) - A negative lookbehind to prevent a preceded whitespace. (?<!\s) - 一个否定的向后看,以防止前面的空格。
    • ) - Close 1st capture group. ) - 关闭第一个捕获组。
  • : - Match a colon. : - 匹配一个冒号。
  • ( - Open 2nd capture group: ( - 打开第二个捕获组:
    • [^:]* - 0+ times any character other than colon. [^:]* - 0+ 次除冒号以外的任何字符。
    • ) - Close 2nd capture group. ) - 关闭第二个捕获组。
  • $ - End string anchor. $ - 结束字符串锚。

 const regex = /^([^:]*(?<:\s)):([^;]*)$/: [ "I am, learning javascript": "I am. learning javascript" ].forEach(s => console.log(s,replace(regex: "$1;$2")));

I would use a replace method with a regex which captures both the optional whitespace (also as sequence) and the colon...我将使用带有正则表达式的replace方法,该方法捕获可选的空格(也作为序列)和冒号......

/(\s*)(:)/g /(\s*)(:)/g

The callback function of replace gets passed as its arguments... replace的回调 function 作为其 arguments 传递...

  1. the entire match... eg either ':' or just ':'整场比赛......例如':'或只是':'
  2. the 1st capture for the whitespace... eg either ' ' or just ''空白的第一次捕获...例如' '或只是''
  3. the 2nd capture for the colon... of cause always ':'结肠的第二次捕获......原因总是':'

Thus within a callback function one can test for the existence of whitespace(s).因此,在回调 function 中,可以测试是否存在空格。

 function replaceWsColonGroup(match, space, colon) { console.log({ match, space, colon }); return (space || " ") + colon; } const regXWsColonGroup = (/(\s*)(:)/g); console.log( ' I am: learning javascript =>\n', 'I am: learning javascript'.replace(regXWsColonGroup, replaceWsColonGroup), '\n\n' ); console.log( ' I am: learning javascript =>\n', 'I am: learning javascript'.replace(regXWsColonGroup, replaceWsColonGroup), '\n\n' ); console.log( ' I am\n\t: learning javascript =>\n', 'I am\n\t: learning javascript'.replace(regXWsColonGroup, replaceWsColonGroup), '\n' );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

And regarding the OP's first condition, checking the existence of just a single colon, I suggest a split based approach which splits the string at every existing colon and then just checks the resulting array's length property that's value then needs to be exactly 2 .关于 OP 的第一个条件,检查是否只存在一个冒号,我建议使用一种基于split的方法,该方法在每个现有冒号处拆分字符串,然后只检查结果数组的length属性,该属性的 value 然后需要正好是2

 console.log( "... valid...\n", "'I am: learning javascript'.split(':').length...", 'I am: learning javascript'.split(':').length ); console.log( "... invalid...\n", "'I: am: learning javascript'.split(':').length...", 'I: am: learning javascript'.split(':').length );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

Thus, a sanitizer script would look pretty much like the following one...因此,一个消毒脚本看起来很像下面的......

 function sanitizeExpression(str) { return (String(str).split(':').length === 2)? String(str).replace((/(\s*)(:)/g), (_, $1, $2) => ($1 || ' ') + $2): str } console.log( sanitizeExpression() ); console.log( sanitizeExpression(null) ); console.log( sanitizeExpression('foo bar baz') ); console.log( sanitizeExpression('I:am:learning javascript') ); console.log( sanitizeExpression('I am: learning javascript') ); console.log( sanitizeExpression('I am\n\t: learning javascript') );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

If string has only 1 colon, if so,then check whats the element coming in front of colon, if it do have space dont do anything and if it dont have space, add a space如果字符串只有 1 个冒号,如果是,则检查冒号前面的元素是什么,如果有空格则不做任何事情,如果没有空格,则添加空格

Javascript code - Javascript 代码 -

var term= "I am: learning javascript ";
if(term.indexOf(':') === term.lastIndexOf(':')) {

      var indexOfColon = term.indexOf(':');
      var nextChar = term.charAt(indexOfColon + 2);
     
      if(nextChar != ' '){
               
               term = term.slice(0,indexOfColon+1) + ' ' + term.slice(indexOfColon+1)
       }
}
console.log(term) ==> "I am:  learning javascript ";

Added a space after colon.在冒号后添加一个空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查字符串中的某个字符是否在另一个字符之后? - How to check whether a certain character in string comes after another character? 如何检查字符串中的字符是否是 JavaScript 中的特定字符? - How do I check whether a character in a string is a specific character in JavaScript? 如何检查字符串中的最后一个字符是否为“空格”? - How to check if last character in a string is 'space'? 如何检查特定字符串中是否存在任何特殊字符 - how to check whether any special character is present in a particular string 没有正则表达式,如何检查数组中的单词是否包含在字符串中? - How to check whether word within array is included in string, without regex? 如何检查字符串是否仅包含一个空格? - How to check if string contains ONLY one space? 如何检查一个 class 是否继承了另一个 class? - How to check whether one class is inhereted of another class? 如何检查输入是否为单词、空格和换行符? - How to check whether inputs are words, space and newLine? 如何检查一个字符串是否包含另一个字符串中的任何字符? - How to check if a string contains any character from another string? Javascript正则表达式来检查一个字符串是否是某个字符的组合 - Javascript regular expression to check whether a string is a combination of certain character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM