javascript - count spaces before first character of a string - javascript

What is the best way to count how many spaces before the fist character of a string?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';

Use String.prototype.search
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT:
You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
' '.search(/\S|$/)

Using the following regex:
/^\s*/
in String.prototype.match() will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.
pttrn = /^\s*/;
str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;
str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;
str2 = ' twospaces';
len2 = str2.match(pttrn)[0].length;
Remember that this will also match tab chars, each of which will count as one.

You could use trimLeft() as follows
myString.length - myString.trimLeft().length
Proof it works:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft

str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);
arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);
arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);
Here:
I have used regular expression to count the number of spaces before the fist character of a string.
^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group

str.match(/^\s*/)[0].length
str is the string.

Related

how to split string every 2 character

var alphabet = "FIN SLHOJVHEN GYKOHU";
I want to split it every 2 character so it would print
"I LOVE YOU "
I already try this but it didn't work
for (var i = 0 ; i \< alphabet.length ; i+=2 ){
alphabet.split(i)
correct me please
You can transform the string into an array, filter it and make it a string again.
let alphabet = "FIN SLHOJVHEN GYKOHU";
alphabet = [...alphabet].filter((_, i) => i%2).join("");
console.log(alphabet); //I LOVE YOU;
Also this one results in I LOVE YOU (regex101 demo).
// the string
let alphabet = 'FIN SLHOJVHEN GYKOHU';
// capture ^ start or chr, match latter chr
alphabet = alphabet.replace(/(^|.)./g, '$1');
console.log(alphabet);
Since the split function will split the given string by the delimiter you passed, it seems to me that you wish to first split the words (using empty space) contained in the encoded string and only then take only the characters at even positions to include in the decoded string.
This is a demo achieving that:
const encoded = "FIN SLHOJVHEN GYKOHU";
const words = encoded.split(' ');
let decoded = '';
words.forEach((word)=>{
for (let i=1;i<word.length;i+=2){
decoded += word[i];
}
decoded += ' ';
});
console.log(decoded);
Using a regex replacement approach we can try:
var alphabet = "FIN SLHOJVHEN GYKOHU";
var output = alphabet.replace(/[A-Z]([A-Z]|(?=\s))/g, "$1");
console.log(output);
Here is an explanation of the regex pattern:
[A-Z] match a single (odd) uppercase letter
( open capture
[A-Z] an uppercase letter
| OR
(?=\s) lookahead and find a space
)
In other words, we match an odd letter and then capture the next letter, unless that odd letter happen to be the last in the word. Then we replace with just the captured even letter, if available.
you already have different ways to do it, I'm adding one, so you'll get totally confused! hehe
This one is recursive:
we take your string alphabet
first 2 letters (every 2)
last one of this 2 characters string is stored in toPrint variable
delete the first 2 characters from alphabet
... loop till alphabet empty
Your toPrint has I Love You
Certainly not the fastest one, but nice.
let alphabet = "FIN SLHOJVHEN GYKOHU";
let toPrint = '';
do {
let temp = alphabet.slice(0, 2);
toPrint += temp[1];
alphabet = alphabet.slice(2, alphabet.length);
} while (alphabet !== '');
console.log(toPrint);
You can start your loop at 1 as you want every second character, and note that \< should be <
In the loop, i is the position of the character, so you would still have to get the character for that position and then assemble the resulting string.
var alphabet = "FIN SLHOJVHEN GYKOHU";
var result = "";
for (var i = 1; i < alphabet.length; i += 2) {
result += alphabet[i];
}
console.log(result);
If you want to take the spaces into account and only get the 2nd non whitespace character you might:
get the separate words by splitting on whitespace chars
remove the empty entries
join every second character to a string
join the parts from the initial split with a space
const alphabet = " FIN SLHOJVHEN GYKOHU ";
const result = alphabet
.split(/\s+/)
.filter(Boolean)
.map(s => s.split("").filter((s, i) => i % 2).join(""))
.join(" ");
console.log(result);
If you have a browser where a positive lookbehind for a regex is supported:
const alphabet = " FIN SLHOJVHEN GYKOHU ";
const result = alphabet
.split(/\s+/)
.filter(Boolean)
.map(s => s.match(/(?<=^(?:..)*.)./g).join(""))
.join(" ");
console.log(result);
var alphabet = "FIN SLHOJVHEN GYKOHU";
const arrayAlpha = alphabet.split('');
let stringToPrint = '';
for(let i=1; i<arrayAlpha.length; i+=2){
stringToPrint = stringToPrint + arrayAlpha[i]
}
console.log(stringToPrint)

How can I replace a character in a string only if it's followed by a uppercase letter?

I am trying to replace a specific character ( "," -> this is the specific character in my case) in a string only if it's followed by a uppercase letter, but no matter how I try it doesn't work. Does anyone know a good way of doing this ?
const p = 'The ,quick brown ,Fox jumps over the lazy Dog.';
console.log(p.replace(/,([A-Z])/g, 'xxx$1'));
var str1 = "test,Test";
var newstr ;
var index1 = str1.indexOf(',');
if(str1.charAt(index1+1) == str1.charAt(index1+1).toUpperCase()) {
var newstr = str1.substr(0, index1) + "*" + str1.substr(index1+1 , str1.length);
}else {
newstr = str1;
}
console.log(newstr);

How to apply a regex just for a part of string?

I have a string like this:
var str = "this is test
1. this is test
2. this is test
3. this is test
this is test
1. this test
2. this is test
this is test";
Also I have this regex:
/^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m
This capturing group $1 returns 2 from above string.
Now I have a position number: 65 and I want to apply that regex in this range of the string: [0 - 65]. (So I have to get 3 instead of 2). In general I want to limit that string from first to a specific position and then apply that regex on that range. How can I do that?
The simplest way is to apply it to just that substring:
var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
// Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^
Example:
var str = "this is test\n1. this is test\n2. this is test\n3. this is test\nthis is test\n1. this test \n2. this is test\nthis is test";
var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
// Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^
document.body.innerHTML = match ? "First capture: [" + match[1] + "]" : "(no match)";
Maybe such a build can help (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}

How to add newline after a repeating pattern

Assume that there is a string like this:
var content = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20";
I want to add <br /> after every 5 dots.
So, the result should be:
1.2.3.4.5.<br />
6.7.8.9.10.<br />
11.12.13.14.15.<br />
16.17.18.19.20.<br />
I want to do this without a for loop. Is it possible with just regex?
i'm doing this with this code;
regenerate:function(content,call){
var data2;
var brbr = content.replace(/[\u0250-\ue007]/g, '').match(/(\r\n)/g);
if (brbr !== "") {
data2 = content.replace(/[\u0250-\ue007]/g, '').replace(/(\r\n)/gm, "<br><br>");
} else {
data2 = content.replace(/[\u0250-\ue007]/g, '');
}
var dataArr = data2.split(".");
for (var y = 10; y < dataArr.length - 10; y += 10) {
var dataArrSpecific1 = dataArr[y] + ".";
var dataArrSpecific2 = dataArr[y] + ".<br>";
var dataArrSpecificBosluk = dataArr[y + 1];
var data3 = data2.replace(new RegExp(dataArrSpecific1.replace(/[\u0250-\ue007]/g, ''), "g"), "" + dataArrSpecific2.replace(/[\u0250-\ue007]/g, '') + "");
data3 = data3.replace(new RegExp(dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, ''), "g"), " " + dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, '') + "");
data2 = data3;
}
call(data2.replace(/[\u0250-\ue007]/g, ''));
}
Actually , i want to refactoring this code
Working bin:http://jsbin.com/dikifipelo/1/
var string = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20." ;
string = string.replace(/(([^\.]+\.){5})/g, "$1<br/>");
Works with any type and length of characters between the dots.
Explanation:
The pattern /(([^.]+.){5})/g can be broken down as such:
[^\.] - any character that is not a dot
[^\.]+ - any character that is not a dot, one or more times
[^\.]+\. - any character that is not a dot, one or more times, followed by a dot
([^\.]+\.){5} - any character....dot, appearing five times
(([^\.]+\.){5}) - any...five times, capture this (all round brackets capture unless told not to, with a ?: as the first thing inside them)
the /g/ flag makes it so that the whole string is matched - ie, all matches are found
"$1" represents the results of the first group (or bracket)
so, the replace function finds all instances of the pattern in the string, and replaces them with the match itself + a line break (br).
Once you learn regular expressions, life is never the same.

JS Regex - Match each not escaped specific characters

I'm trying to make a Regex in JavaScript to match each not escaped specific characters.
Here I'm looking for all the ' characters. They can be at the beginning or the end of the string, and consecutive.
E.g.:
'abc''abc\'abc
I should get 3 matchs: the 1st, 5 and 6th character. But not 11th which escaped.
You'll have to account for cases like \\' which should match, and \\\' which shouldn't. but you don't have lookbehinds in JS, let alone variable-length lookbehinds, so you'll have to use something else.
Use the following regex:
\\.|(')
This will match both all escaped characters and the ' characters you're looking for, but the quotes will be in a capture group.
Look at this demo. The matches you're interested in are in green, the ones to ignore are in blue.
Then, in JS, ignore each match object m where !m[1].
Example:
var input = "'abc''abc\\'abc \\\\' abc";
var re = /\\.|(')/g;
var m;
var positions = [];
while (m = re.exec(input)) {
if (m[1])
positions.push(m.index);
}
var pos = [];
for (var i = 0; i < input.length; ++i) {
pos.push(positions.indexOf(i) >= 0 ? "^" : " ");
}
document.getElementById("output").innerText = input + "\n" + pos.join("");
<pre id="output"></pre>
You can use:
var s = "'abc''abc\\'abc";
var cnt=0;
s.replace(/\\?'/g, function($0) { if ($0[0] != '\\') cnt++; return $0;});
console.log(cnt);
//=> 3

Categories