How to retrieve a word from the string - javascript

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

Related

Replace all occurences of custom tag with URL in it [JS]

I'm making an online text editor for a website I'm building, and I use custom tags for the markup.
To make it easier to read, the markup is highlighted by blue, which I do buy using the following function:
var imgOccurences = (informationText.match(/\[img/gi)).length;
for(var i = 0; i < imgOccurences; i++){
var imgLocation = informationText.indexOf('[img');
var endImgLocation = informationText.indexOf(']', imgLocation+1);
if(imgLocation != -1 && endImgLocation != -1){
var informationTextTemp1 = informationText.slice(0, imgLocation);
var informationTextTemp2 = informationText.slice(endImgLocation+1, -1);
var informationTextTemp3 = informationText.slice(imgLocation, endImgLocation+1);
informationTextTemp3 = "<span class='highlightWord'>"+informationTextTemp3+"</span>";
informationText = informationTextTemp1 + informationTextTemp3 + informationTextTemp2;
}
}
However the problem I face is that, when normalizing the text to HTML, I cannot use regex expressions, which I was previously using with the other tags, on the [img] tag, due to the fact that I wanted to highlight the image tag, and all of its contents, which includes a URL.
So I decided to count up all the occurrences of just the '[img' part of the [img] tag and then look for the next occurrence of ']', then slice it out of the normal text, then highlight it using a span, and then add it back to the normal text, while I put it in a for loop.
However only the first occurrence of the [img] tag is highlighted, and I am unsure as to how I should deal with this. Any help would be appreciated.
Basically I need to get everything which looks like: [img src='www.example.com/image.png']and make it look like:<span class='highlightWord'>[img src='example.com/image.png']</span> and then put it into the .innerHTML of the div called textHighlights.
Expected result:
The result I got:
You can do it much simpler since the .replace method accepts a regular expression as a parameter for the matching string.
informationText = informationText.replace(/(\[img.+?\])/gi, '<span class="highlightWord">$1</span>');
The above will replace all matches directly (by wrapping them in the span you want)

Remove one line in txt file ( NODE.js)

I make a text file "foo\nbar\nbas"
When i append coke(with adding \n), then the file will be "foo\nbar\nbas\ncoke"
I want to remove the foo.
Help me!
Fo your use case that you have provided, a simple answer is split on \n, remove the first item, add the new item to the end, and join the array to form your new string.
var parts = "foo\nbar\nbas".split("\n").slice(1);
parts.push("coke");
var updated = parts.join("\n");
Other option is to use indexOf to find the first occurrence of \n and substring to select the portion of the string, then it is a simple concatenation.
var str = "foo\nbar\nbas";
var position = str.indexOf("\n")+1;
var updated = str.substring(position) + "\ncoke";
You can use simple string manipulation if your task is not complicated by further constraints. Such is as follows:
var fileContents = "foo\nbar\nbas";
// Read Text File, in this case, I have set it.
fileContents = fileContents.replace("foo\n", "");
fileContents += "\ncoke";
// Write back to file

How to find a substring only in the text portion of an HTML string, with Javascript?

UPDATE: I am no longer specifically in need of the answer to this question - I was able to solve the (larger) problem I had in an entirely different way (see my comment). However, I'll check in occasionally, and if a viable answer arrives, I'll accept it. (It may take a week or three, though, as I'm only here sporadically.)
I have a string. It may or may not have HTML tags in it. So, it could be:
'This is my unspanned string'
or it could be:
'<span class="someclass">This is my spanned string</span>'
or:
'<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>'
or:
'<span class="no-text"><span class="silly-example"></span></span><span class="some-class">This is my spanned string</span>'
I want to find the index of a substring, but only in the portion of the string that, if the string were turned into a DOM element, would be (a) TEXT node(s). In the example, only in the part of the string that has the plain text This is my string.
However, I need the location of the substring in the whole string, not only in the plain text portion.
So, if I'm searching for "span" in each of the strings above:
searching the first one will return 13 (0-based),
searching the second will skip the opening span tag in the string and return 35 for the string span in the word spanned
searching the third will skip the empty span tag and the openings of the two nested span tags, and return 91
searching the fourth will skip the nested span tags and the opening of the second span tag, and return 100
I don't want to remove any of the HTML tags, I just don't want them included in the search.
I'm aware that attempting to use regex is almost certainly a bad idea, probably even for simplistic strings as my code will be encountering, so please refrain from suggesting it.
I'm guessing I will need to use an HTML parser (something I've never done before). Is there one with which I can access the original parsed strings (or at least their lengths) for each node?
Might there be a simpler solution than that?
I did search around and wasn't been able to find anyone ask this particular question before, so if someone knows of something I missed, I apologize for faulty search skills.
The search could loop through the string char by char. If inside a tag, skip the tag, search the string only outside tags and remember partial match in case the text is matched partially then interrupted with another tag, continue the search outside the tag.
Here is a little function I came up with:
function customSearch(haysack,needle){
var start = 0;
var a = haysack.indexOf(needle,start);
var b = haysack.indexOf('<',start);
while(b < a && b != -1){
start = haysack.indexOf('>',b) + 1;
a = haysack.indexOf(needle,start);
b = haysack.indexOf('<',start);
}
return a;
}
It returns the results you expected based in your examples. Here is a JSFiddle where the results are logged in the console.
Let's start with your third example:
var desiredSubString = 'span';
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
Remove all HTML elements from entireString, above, to establish textString:
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
You can then find the index of the start of the textString within the entireString:
var indexOfTextString = entireString.indexOf(textString);
Then you can find the index of the start of the substring you're looking for within the textString:
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
Finally you can add indexOfTextString and indexOfSubStringWithinTextString together:
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
Putting it all together:
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var desiredSubString = 'span';
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
var indexOfTextString = entireString.indexOf(textString);
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
You could use the browser's own HTML parser and XPath engine to search only inside the text nodes and do whatever processing you need.
Here's a partial solution:
var haystack = ' <span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var needle = 'span';
var elt = document.createElement('elt');
elt.innerHTML = haystack;
var iter = document.evaluate('.//text()[contains(., "' + needle + '")]', elt).iterateNext();
if (iter) {
var position = iter.textContent.indexOf(needle);
var range = document.createRange();
range.setStart(iter, position);
range.setEnd(iter, position + needle.length);
// At this point, range points at the first occurence of `needle`
// in `haystack`. You can now delete it, replace it with something
// else, and so on, and after that, set your original string to the
// innerHTML of the document fragment representing the range.
console.log(range);
}
JSFiddle.

Search a string

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

Select text string before comma, set it to uppercase

JS Fiddle Example
OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.
I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:
function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}​
Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?
function splitLastName(){
$('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
var names = v.split(',');
return '<span class="isUppercase">' +names[0] + '</span>,' + names[1];
});
}
Fiddle
.html() docs
The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:
function splitLastName() {
$('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
var names = $(this).text().split(',');
$(this).empty().append($('<span>', {
'class': 'isUppercase',
text: names[0]
}), ',' + names[1]);
});
}
Fiddle
Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.
The problem is you are trying to split a JQuery object.
I have updated your example: See here
function splitLastName(){
var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
var html = element.html();//get the contents of the DIV element
var splitNameArray = html.split(",");//Split the value with comma
var lastName = splitNameArray[0];//store the last name
var firstName = splitNameArray[1];//store the first name
var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
The problem occurs with this line:
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
The notation:
$('< some name >')
is a jQuery selector that selects an element. If you type this into your console (replacing < some name > with your selector) in your browser you'll see that it returns an object not a string. So your code is trying to split an object. I don't know where the string is located (div, span, input box etc.) but you need to pull the string to do the split. If your string is text in a div or span use:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').text()).split(",");
as this will grab the string contained in that selector and then perform the split on it. Likewise, if it is in an input you will need to use the proper handler to get the value:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').val()).split(",");
This will pull the value from an input and then perform the split. If your string is in html then you could alternatively grab it using the following notation:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').html()).split(",");
This will pull the html and perform the respective split operation.
Hope this helps.

Categories