I have got following two strings:
1. 'TestKey : TestValue'
2. '"Test : Key" : Test:Value'
Here I want to split both strings by the first occurrence of the char colon (:) and I have to ignore the colon if the string part is enclosed with double quotes.
I have to split the first string as like below:
[TestKey, TestValue]
And need to split the second string like below:
[Test : Key, Test:Value]
Any help would be greatly appreciated in JavaScript with or without Regex.
We need to split first and check the double quotes in every set of data anf if not found add them though join.
var str = '"Test : Key" : Test:Value';
var arr = str.split(':');
var newArr = [];
var ktr = '';
for(let i=0;i<arr.length;i++) {
if(arr[i].indexOf('"') !== -1) {
ktr += arr[i] + ':';
} else {
newArr.push(arr[i]);
}
}
if(ktr !== '') {
ktr = ktr.substring(0,ktr.length-1);
newArr.unshift(ktr);
}
console.log(newArr.join(':'));
Here is a piece of working code using a RegExp testing the strings you provided as examples:
var regex = /\"{0,1}([^"]*)\"{0,1}\s:\s\"{0,1}([^"]*)\"{0,1}/g;
var str1 = 'TestKey : TestValue';
var str2 = '"Test:Key" : Test:Value';
var str3 = '"Test : Key" : Test:Value';
var firstArray = regex.exec(str1);
regex.lastIndex = 0; //reset the regex
var secondArray = regex.exec(str2);
regex.lastIndex = 0; //reset the regex
var thirdArray = regex.exec(str3);
regex.lastIndex = 0; //reset the regex
//remove the first element of each array, which is the whole string
firstArray.shift();
secondArray.shift();
thirdArray.shift();
Hope it helps.
You can test the RegExp here: https://regex101.com/r/PV123v/1
Related
I have the following string:
var myString = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>';
how can i get with the least code the someExtraStuff.fileExt section?
should i do indexOf {{appName}} and then until the next "/> ?
You could search for the pattern {{appName}} and take all characters who are not quotes. Then take the second element of the match.
var string = '<p><i class="someclass"></i><img scr="somesource"/><img class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/><span class="someclass"></span></p>',
substring = (string.match(/\{\{appName\}\}([^"]+)/) || [])[1]
console.log(substring);
You can do this with three methods
// 1 option
For single match
var regex = /\{\{appName\}\}([^"]+)/;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
console.log(myString.match(regex)[1]);
// 2 option
For multiple matches
var regex = /\{\{appName\}\}([^"]+)/g;
var myString = '<p class="somefunnyclass" id="{{appName}}someExtraStuff.fileExt"/>';
var temp;
var resultArray = [];
while ((temp = regex.exec(myString)) != null) {
resultArray.push(temp[1]);
}
console.log(resultArray);
// 3 option For indexOf
var firstIndex= myString.indexOf("{{appName}}");
var lastIndex =firstIndex+ myString.substring(firstIndex).indexOf('"/>')
var finalString = myString.substring(firstIndex,lastIndex).replace("{{appName}}","");
console.log(finalString);
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");
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>
I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));
I would like to replace every other comma in a string with a semicolon.
For example:
1,2,3,4,5,6,7,8,9,10
would become
1;2,3;4,5;6,7;8,9;10
What would be the regexp to do this? An explanation would be great.
Thank you :)
var myNums = "1,2,3,4,5,6,7,8,9,10";
myNums.replace(/(.*?),(.*?,)?/g,"$1;$2");
That'll do it.
var str = '1,2,3,4,5,6,7,8,9,10';
str.replace(/,(.*?,)?/g, ';$1');
// Now str === "1;2,3;4,5;6,7;8,9;10"
You would do something like this:
myString.replace(/,/g, ';');
You could use this regex pattern
([^,]*),([^,]*),?
And replace with $1;$2,. The question mark on the end is to account for the lack of a comma signaling the end of the last pair.
For example...
var theString = "1,2,3,4,5,6,7,8,9,10";
theString = theString.replace(/([^,]*),([^,]*),?/ig, "$1;$2,"); //returns "1;2,3;4,5;6,7;8,9;10,"
theString = theString.substring(0, theString.length - 1); //returns "1;2,3;4,5;6,7;8,9;10"
A non-regex answer:
function alternateDelims(array, delim_one, delim_two) {
var delim = delim_one,
len = array.length,
result = [];
for(var i = 0; i < len; i += 1) {
result.push(array[i]);
if(i < len-1) { result.push(delim); }
delim = (delim === delim_one) ? delim_two : delim_one;
}
return result.join('');
}
nums = "1,2,3,4,5,6,7,8,9,10"
alternateDelims(nums.split(','), ';', ',');