get string before and after specific character - javascript

I want to split a string for a fill in string type with no whitespace for examples:
£____
____$
42____$
i would like a way to split the string so i can know what the characters before and after _.
Desired results:
`£____` => before = '£', after = null
`____$` => before = null, after = '$'
`42____$` => before = '42', after = '$'
I though of tried using word.replace('_', ' ') to split by whitespace but it returning the same string as the old one(i'm still a novice at javascript).

You may try a regex string split here:
var inputs = ["£____", "____$", "42____$"];
for (var i=0; i < inputs.length; ++i) {
var parts = inputs[i].split(/_+/);
console.log("before = " + parts[0] + ", after = " + parts[1]);
}

You can try Regex.
Something Like This
[^_;]

Related

Concatenate string in typescript/javascript

EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.
I am trying to concatenate a string such that I get the following output:
"OR("1admin", "2admin")"
But the output I keep on getting is
"OR(\"1admin\", \"2admin\")"
Sample code
var str = "OR("
for (let i = 1; i < 3; i++) {
str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)
I have tried using regex and string split.
eg.
.replace(/'/g, '"') This when i tried something like this "'" + i + "admin" + "', " and tried to replace ' with "
.split('\\').join('').trim() This also didn' work.
What am I doing wrong?
As mentioned, you already got the correct result in your original snippet.
If the character escape syntax seems curious to you, I'd recommend something like the following using template strings.
You can write the " in template strings unescaped and use interpolation to print your variables.
Edit: Seems like you want JSON formatting. You can use JSON.stringify for that. JSON formatted strings will contain escape characters that show up in console.log output.
const f = (n, s) => {
const a = new Array(n)
.fill()
.map((_, i) => `"${i + 1}${s}"`);
return `OR(${a.join(', ')})`;
}
console.log(`output: ${f(2, "admin")}`)
console.log(`json-formatted: ${JSON.stringify(f(2, "admin"))}`)
This seems to do the job:
const NUM_ADMINS = 2;
const CONCAT_STRING =
`OR(${
Array(NUM_ADMINS)
.fill()
.map((_, idx) => `"${idx + 1}admin"`)
.join(", ")})`;
It creates a new array with the needed number of admins, then maps it to strings in th form "admin", joins with a comma and a space. And then it it is all wrapped in a "OR()" string.
var str = '"OR("'
var adm = 'admin"'
var end = ')"'
for (let i = 1; i < 3; i++) {
str += i + adm + ', '
}
str = str.trim().substring(0, str.length - 2)
str += end
console.log(str);
try running this snippet. if the implementation is fyn for you. Result is what you expected.

regex (only 1 dot)

I have a regEx where I replace everything whats not a number:
this.value.replace(/[^0-9\.]/g,'');
how can i make sure it will only allow 1 dot
(the second dot will be replaced like the others)
(I know you can use input just number (thats not an option in this project for me))
You can use a simple trick of:
splitting a string by ., and then only joining the first two elements of the array (using .splice(0,2)) with a . and the rest with nothing
using a simple regex pattern to replace all non-digit and non-period characters: /[^\d\.]/gi
Here is an example code:
// Assuming that `yourString` is the input you want to parse
// Step 1: Split and rejoin, keeping only first occurence of `.`
var splitStr = yourString.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Step 2: Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
Proof-of-concept example:
var tests = [
'xx99',
'99xx',
'xx99xx',
'xxxx999.99.9xxx',
'xxxx 999.99.9 xxx',
'xx99xx.xx99xx.x9',
'xx99xx.99x.9x',
'xx99.xx99.9xx'
];
for (var i = 0; i < tests.length; i++) {
var str = tests[i];
// Split and rejoin, keeping only first occurence of `.`
var splitStr = str.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
console.log('Original: ' + str + '\nParsed: ' + parsedStr);
}
I resolved it with.
this.value = this.value.replace(/.*?(\d+.\d+).*/g, "$1");

Why isnt this string parsing function working? [duplicate]

This question already has answers here:
How to remove spaces from a string using JavaScript?
(15 answers)
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 6 years ago.
I created a function to delete the spaces out of a string and return the strings length with out spaces, however the function is deleting more then just the spaces. Also is there a better way of accomplishing this, assuming this function can be fixed.
let string="This string is going to lose characters";
function charLength(str){
let strArray=str.split("");
let output="";
for(let i=0; i < strArray.length; i++){
if(strArray[i]===" "){
strArray.splice(strArray[i],1);
}
else{
output+=strArray[i];
}
}
return output.length // + " " output, if I were to add this you would see its deleting characters
}
charLength(string);//returns "27 Thistringsoingooseharacters", not "33 Thisstringisgoingtolosecharacters"
When you remove a character from the string you'll have to go back one step (i--) st the loop won't skip a character (for(... ; i++)). Like this:
if (strArray[i] === " ") {
strArray.splice(strArray[i], 1);
i--; // ge back one step if we remove one character.
}
Snippet:
let string = "This string is not going to lose characters";
function charLength(str) {
let strArray = str.split("");
let output = "";
for (let i = 0; i < strArray.length; i++) {
if (strArray[i] === " ") {
strArray.splice(strArray[i], 1);
i--;
} else {
output += strArray[i];
}
}
return output;
}
console.log(charLength(string));
If you want to count characters that are not spaces:
Then just make a counter that will count the characters that are not spaces like this:
let string = "This string is not going to lose characters";
function charLength(str) {
let counter = 0; // the counter
for (let i = 0; i < str.length; i++) { // for each character in the string
if(str.charAt(i) !== ' ') // if the character is not a space
counter++; // increment the counter
}
return counter;
}
console.log(charLength(string));
The reason why characters get lost, is because the list is modified inside the loop.
for(let i=0; i < strArray.length; i++){
if(strArray[i]===" "){
strArray.splice(strArray[i],1); // Items are removed here
...
When you remove an character i, the next character will take its place.
You could maybe use the replace function instead like this:
string.replace(/ /gi, "").length
Use regex.
var str = 'This string is going to lose characters';
// The substituted value will be contained in the result variable
const result = str.replace(/\s/g, '');
console.log('Substitution result: ', result.length);
You don't need a regex: str.replace(" ","") is already doing that.
Instead of this line here:
strArray.splice(strArray[i],1);
Try using this:
strArray.splice(strArray[i],0);
Just replaces the 1 with 0
This is much simpler than you are doing. You can just use the .replace() string method which can take a string literal to replace or a regular expression.
function charLength(str){
// Create a new string that is the same as the passed in one, but with the spaces stripped out
// The syntax / / denotes a regular expresion (regEx) object
// The s+ denotes to look for one or more spaces in a row
// The g denotes a global search and replace througout the string
var newStr = str.replace(/\s+/g, "");
console.log("\"" + str + "\" has: " + str.length + " characters.");
console.log("\"" + newStr + "\" has: " + newStr.length + " characters.");
}
charLength("This string is going to lose characters");
You could use eiter a regular expression for filtering space
var string = "This string is going to lose characters",
result = [...string].filter(RegExp.prototype.test.bind(RegExp('[^ ]'))).join('');
console.log(result);
console.log(result.length);
Or just test for space.
var string = "This string is going to lose characters",
result = [...string].filter(a => a !== ' ').join('');
console.log(result);
console.log(result.length);

How can I replace single digit numbers within a string without affecting 2 digit numbers in that string

I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>

Regex to remove all characters that are repeated

I'm looking for a regex that will remove all characters that have been repeated in a string. I already solved this using a loop. Just wondering if there is a regex that can do the same.
this is what i have so far:
function onlyUnique(str) {
var re = /(.)(?=.*\1)/g
return str.replace(re, '');
}
This string:
"rc iauauc!gcusa_usdiscgaesracg"
should end up as this:
" !_de"
You can use Array#filter with Array#indexOf and Array#lastIndexOf to check if the element is repeated.
var str = "rc iauauc!gcusa_usdiscgaesracg";
// Split to get array
var arr = str.split('');
// Filter splitted array
str = arr.filter(function (e) {
// If index and lastIndex are equal, the element is not repeated
return arr.indexOf(e) === arr.lastIndexOf(e);
}).join(''); // Join to get string from array
console.log(str);
document.write(str);
well, no idea if regex can do that, but you could work it out using for loop, like:
function unikChars(str) {
store = [];
for (var a = 0, len = str.length; a < len; a++) {
var ch = str.charAt(a);
if (str.indexOf(ch) == a && str.indexOf(ch, a + 1) == -1) {
store.push(ch);
}
}
return store.join("");
}
var str = 'rc iauauc!gcusa_usdiscgaesracg';
console.log(unikChars(str)); //gives !_de
Demo:: jsFiddle
Your regex searches pairs of duplicated characters and only removes the first one. Therefore, the latest duplicate won't be removed.
To address this problem, you should remove all duplicates simultaneously, but I don't think you can do this with a single replace.
Instead, I would build a map which counts the occurrences of each character, and then iterate the string again, pushing the characters that appeared only once to a new string:
function onlyUnique(str) {
var map = Object.create(null);
for(var i=0; i<str.length; ++i)
map[str[i]] = (map[str[i]] || 0) + 1;
var chars = [];
for(var i=0; i<str.length; ++i)
if(map[str[i]] === 1)
chars.push(str[i]);
return chars.join('');
}
Unlike indexOf, searches in the hash map are constant on average. So the cost of a call with a string of n characters will be n.
If you want to do it with a regex, you can use your own regex with a callback function inside a replace.
var re = /(.)(?=.*\1)/g;
var str = 'rc iauauc!gcusa_usdiscgaesracg';
var result = str;
str.replace(re, function(m, g1) {
result = result.replace(RegExp(g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), '');
});
document.getElementById("r").innerHTML = "'" + result + "'";
<div id="r"/>
The idea is: get the duplicated character, and remove it from the input string. Note that escaping is necessary if the character might be a special regex metacharacter (thus, g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") is used).
Another idea belongs to Washington Guedes in his deleted answer, I just add my own implementation here (with removing duplicate symbols from the character class and escaping special regex chars):
var s = "rc iauauc!gcusa_u]sdiscgaesracg]";
var delimiters= '[' + s.match(/(.)(?=.*\1)/g).filter(function(value, index, self) { // find all repeating chars
return self.indexOf(value) === index; // get unique values only
}).join('').replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ']'; // escape special chars
var regex = new RegExp(delimiters, 'g'); // build the global regex from the delimiters
var result = s.replace(regex, ''); // obtain the result
document.getElementById("r2").innerHTML = "'" + result + "'";
<div id="r2"/>
NOTE: if you want to support newline symbols as well, replace . with [^] or [\s\S] inside the regex pattern.
function onlyUnique(str) {
// match the characters you want to remove
var match = str.match(/(.)(?=.*\1)/g);
if (match) {
// build your regex pattern
match = '[' + match.join('') + ']';
}
// if string is already unique return the string
else {
return str
}
// create a regex with the characters you want to remove
var re = new RegExp(match, 'g');
return str.replace(re, '');
}

Categories