javascript get substring between two sets of characters - javascript

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);

Related

How to split string by first occurrence of a char (:) in JavaScript

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

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>

How to find multiple values within curly braces from a string

How to find multiple values within curly braces from a string using JavaScript.
E.g.
string = https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};
I tried with this, /#{[A-Za-z0-9À-ÿ_ .-]*}/ but don't know how to get the values matched.
How can you get the name1, name2 and name3 from the string?
Use a regex to match text surrounded by curly braces. You'll want to use +? to match non-greedily.
var string = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3}";
var matches = string.match(/{.+?}/g);
Now matches is ["{name1}", "{name2}", "{name3}"].
You can use this RegEx.
/{.*?}/g
E.g.
var s = 'https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};';
var res = s.match(/{.*?}/g);
for (var r in res)
{
console.log(res[r]);
}
This outputs
{name1}
{name2}
{name3}
While other answers show how to extract the text with curly brackets, none of them has really answered the question.
How can you get the name1, name2 and name3 from the string?
You can use String#indexOf and String#substring methods.
var str = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};";
// Copy the string
var copy = str;
var index,
matches = []; // To store results
// Till there is string wrapped in curly braces
while ((index = copy.indexOf('{')) !== -1) {
var closingIndex = copy.indexOf('}');
matches.push(copy.substring(index + 1, closingIndex));
// Update the string to remove the first match
copy = copy.substring(closingIndex + 1);
}
console.log(matches);
document.body.innerHTML = '<pre>' + JSON.stringify(matches, 0, 4) + '</pre>';
Using RegEx
/{([^}]*)}/
With global flag.
Regex101 Demo
RegEx Explanation:
{: Match { literally
([^}]*): Match anything that is not } any number of times and put the match result in the first captured group.
}: Match closing bracket }
g: Global flag
In JavaScript, get the results by using RegExp#exec.
var regex = /{([^}]*)}/g;
var str = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};";
var matches = [];
while (match = regex.exec(str)) {
// match[1] is the first captured group
matches.push(match[1]);
}
console.log(matches);
document.body.innerHTML = '<pre>' + JSON.stringify(matches, 0, 4) + '</pre>';
If you want a non-regex syntax (perhaps for more clarity):
var str = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3}";
var bopen = false;
var valIndex = {
istart: 0,
iend: 0
};
values = [];
for (var i = 0 ; i < str.length ; i++) {
var ch = str.charAt(i);
if (ch == '{') {
bopen = true;
valIndex.istart = i;
}
if (ch == '}' && bopen == true){
bopen = false;
valIndex.iend = i;
values.push(str.substring(valIndex.istart + 1, valIndex.iend));
}
}
alert(values);
The alerted result is an array of strings : name1,name2,name3
Here's a JSFiddle.

JavaScript get character in sting after [ and before ]

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));

Find text between two characters and for each, do something

I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
|#main|
#header|
.bananas|
#nav|
etc
</div>
The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here
This just gets the first string. How can I add logic in there to do something for each string?
You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');
You can split like
var my_splitted_var = $('#unused').text().split('|');
One way;
$.each($("#unused").text().split("|"), function(ix, val) {
val = $.trim(val); //remove \r|\n
if (val !== "")
alert(val);
});
One way :
var test_str = $('#unused').text();
while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str = test_str.slice(end_pos,test_str.length);
}
RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');
var result = new Array();
var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
match = regExp.exec(trimmedHtml);
if (match != null) result.push(match[1]);
}
alert(result);
So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.

Categories