简体   繁体   中英

Get all words between two characters and replace - JavaScript

I've got the following text:

Maybe you'll get it next time. You can do it <#Name> ! It is now <#TimeOfDay>, and you still need to get <#Target>.

What I need to do is from the text get all the "tags" (<# TagName ) and replace the tag with some other text such as:

<span class="nonEditable" style="cursor: pointer;">&lt;#TimeOfDay&gt; <span onclick="removePlaceholder(this)"/>
    <span class="closeTag">X</span>
</span>

If I understood you correctly, you are looking for something like this. It uses absolutely positioned elements on a relative div.

 const field = document.getElementById('field') function addTag(target, tagText, xPos, yPos){ const span = document.createElement('span') span.innerHTML = tagText span.style.position = 'absolute'; span.style.top = yPos + 'px' span.style.left = xPos + 'px' target.appendChild(span) } addTag(field, 'Hello', 10, 50) addTag(field, 'SomeTag', 200, 120) 
 #field{ width: 300px; height: 300px; background; #fff; border: 5px solid #333; box-sizing: border-box; position: relative; } 
 <div id="field"></div> 

You can do it with regex (regular expressions).

1.) You need to create a regex that matches the criteria of the searched terms

2.) Then execute the regex.exec() in a while loop to go through all the matches since the regex.exec() method retrieves only one match at a time and remembers the index of the last match. On its next execution regex.exec() will start from that index (the lastIndex ).

3.) replace all occurrences of the match using the str.replace() function


Here are the basics of what you need to know about regular expressions:

The RegExp constructor:

The RegExp constructor creates a regular expression object for matching text with a pattern.

reference: https://developer.mozilla.org/RegExp .

regex.exec():

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. If the match fails, the exec() method returns null (which coerces to false).

reference: https://developer.mozilla.org/RegExp/exec .

regex flags:

The 'g' flag is used with the .exec() method to get iterative progression.

The 'i' flag represents case-insensitive search.

parentheses '()' inside regex:

Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. Once remembered, the substring can be recalled for other use.

reference: https://developer.mozilla.org/Regular_Expressions .


Below is the code example:

Note: the function removePlaceholder() was created as an example to show that the onclick methods of the newly created elements work.

 function removePlaceholder(thisX) { console.log(thisX); // print the element console.log(thisX.innerHTML); // print it's contents console.log(thisX.children[0].innerHTML); // print contents of first child element } var string = "Maybe you'll get it next time. You can do it <#Name> ! It is now <#TimeOfDay>, and you still need to get <#Target>."; // this regex will match only letters az and AZ (the 'i' flag) and space characters // you can add more like 0-9 (all numbers) or \\w+ (any alphanumeric character), etc. // the + sign means one or more characters that are listed inside the bracket [] var regex = new RegExp(/<#([az ]+)>/, 'gi'); // Note the parentheses () var result; var changeTo; while(result = regex.exec(string)) //regex.exec returns NULL when no matches are found { // result[0] -> current match, result[1] -> remembered value from the parentheses changeTo = '<span class="nonEditable" style="cursor: pointer;">&lt;#' + result[1] + '&gt; <span onclick="removePlaceholder(this)"/><span class="closeTag">X</span></span>'; string = string.replace(result[0], changeTo); //replace all occurences of the match } document.getElementById('test').innerHTML = string; //insert the created html into a div // console.log(string); //show the results of the modified string in the console 
 /* CSS just to give the div some borders and padding */ #test { border:1px solid #000; padding:20px; } 
 <!-- Example div --> <div id="test"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM