简体   繁体   English

获取两个字符之间的所有单词并替换-JavaScript

[英]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> ! 您可以执行<#Name>! It is now <#TimeOfDay>, and you still need to get <#Target>. 现在是<#TimeOfDay>,您仍然需要获取<#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: 我需要做的是从文本中获取所有“标签”(< #TagName ),并用其他一些文本替换标签,例如:

<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. 它在相对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). 您可以使用regex (正则表达式)进行操作。

1.) You need to create a regex that matches the criteria of the searched terms 1.)您需要create a regex来匹配搜索词的条件

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. 2.)然后在while loop执行regex.exec()以遍历所有matches因为regex.exec()方法一次仅检索one match at a time并记住最后一个匹配项的索引。 On its next execution regex.exec() will start from that index (the lastIndex ). regex.exec()在其下一次执行时将从该索引( lastIndex )开始。

3.) replace all occurrences of the match using the str.replace() function 3.)使用str.replace()函数替换所有匹配项


Here are the basics of what you need to know about regular expressions: 以下是您需要了解的有关正则表达式的基础知识:

The RegExp constructor: RegExp构造函数:

The RegExp constructor creates a regular expression object for matching text with a pattern. RegExp构造函数创建一个正则表达式对象,以将文本与模式匹配。

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

regex.exec(): regex.exec():

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. 如果匹配成功,则exec()方法返回一个数组并更新正则表达式对象的属性。 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). 如果匹配失败,则exec()方法返回null(强制为false)。

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

regex flags: 正则表达式标志:

The 'g' flag is used with the .exec() method to get iterative progression. 'g'标志与.exec()方法一起使用以获取迭代进度。

The 'i' flag represents case-insensitive search. “ i”标志表示不区分大小写的搜索。

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 . 参考: 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()是作为示例创建的,以显示newly created elementsonclick方法有效。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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