Search a string - javascript

I have a form that user fill with tags like this:
<messageCode>Tag Value 1</messageCode>
<messageVersion>Tag Value 2</messageVersion>
And would like to know if there is a way in Javascript to search the following strings:
String 1 = <messsageCode>
String 2 = Tag Value 1?
I should use index of?

If you insist on parsing xml with regexps and string functions, then
input.match(/<(.*?)>(.*)<\/\1>/)
will return an array, whose [1] element is the tagname and [2] element the content.
Instead, you should use DOMParser to reliably parse the input, and use DOM functions to navigate the result.

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
this will only tell you the start position of welcome. Do you want to retrieve the value?
var str = "tag attr = tag value";
var n = str.indexOf("=");
var res = str.substring(n,);

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Dynamic string cutting

Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.

Finding and replacing html tags conditionally from an html string

I have access to an html string in which I want to search for a specific set of values. So lets say I want to match something from an array...
var array1 = [value1, value2, value3]
If I find value1 in the html string, i want to add a highlight class to that value so it gets highlighted.
var str = htmlString
var res = str.replace('<thead>','<thead class="highlight">');
htmlString = res
Using this i can highlight all the theads, but how could I write it so that I only highlight the theads that contain one of those array values inside of it?
Here's a solution for browser that parses the HTML string into a DOM element, query the DOM tree and manipulate the classList of each selected element, then returns the HTML as a string.
function addClassToElementsByTagName(html, tagName, className) {
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
var elements = tempElement.querySelectorAll(tagName);
elements.forEach(function(element) {
element.classList.add(className);
});
return tempElement.innerHTML;
}
var htmlString = '<table>\n\t<thead>\n\t<tr>\n\t\t<th>Column 1</th>\n\t\t<th>Column 2</th>\n\t\t<th>Column 3</th>\n\t</tr>\n\t</thead>\n</table>';
var result = addClassToElementsByTagName(htmlString, 'thead', 'highlight');
console.log(result);
Gotchas
Keep in mind that element.querySelectorAll() and element.classList.add() are not universally supported. Check out caniuse.com for information regarding each feature.
Also, this is completely dependent on how the browser parses your HTML. If the HTML fails to parse or parses incorrectly, you will experience problems. The .innerHTML property also makes no guarantee that the whitespace provided in the original string will be preserved in the result.

Get text between 2nd and 3rd delimiter in a string - Java script

I have a string like this - tom|harry|john|elizabeth|hopkin|wayne
I would like to extract the value john and wayne from this string and store in variables. How can I do that in jquery or javascript?
If you know which "index" john and wayne is, you can use split() to make it an array and get it from an array with index.
var str = "tom|harry|john|elizabeth|hopkin|wayne"
var arr = str.split("|");
var third = arr[2],
last = arr[arr.length-1];

How to retrieve a word from the string

str = COUPONS
how to get the word COUPONS from the str. the word #homecoupon might change to other word so i can't do the substring method of retrieving the nth position value. the class ="current">COUPONS</a> will always be fixed.
Is there a way i can back track and retrieve the last nth word.
The best way to parse HTML in the browser is to let the browser do it for you.
Create a dummy element in memory, then set its innerHTML to your string. You can then use the regular DOM API to find the text of that anchor element:
var div = document.createElement('div');
div.innerHTML = str;
var word = div.firstChild.textContent;
Here's the fiddle: http://jsfiddle.net/mREFu/
If you still have to support IE < 9, you'll have to use this:
var word = div.firstChild.textContent || div.firstChild.innerText;
Or you could get the text from the text node:
var word = div.firstChild.childNodes[0].nodeValue;
If it's an actual string not a part of a web page :
var str = 'COUPONS';
var word = str.match(/"current">(.*?)</);
if(word) word = word[1]; //== COUPONS
Or if you're using jQuery and that's an actual web page you can go :
$('a.current').each(function(){
alert($(this).text());
});
Using substring() and indexof() you can do this.
str = 'COUPONS';
// get rid of </a> assuming the string always ends with it
var x = str.substring(0,str.length-4);
// use the fixed part to get the value you want
alert(x.substring(x.indexOf('class ="current">')+17))
OR
str = 'COUPONS';
fixedPart = 'class ="current">';
// use the fixed part to get the value you want assuming str always ends with </a>
alert(str.substring(str.indexOf(fixedPart)+fixedPart.length, str.length-4))

Categories